6

The difference between any and unknown type in TypeScript

 3 years ago
source link: https://pawelgrzybek.com/the-difference-between-any-and-unknown-type-in-typescript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The difference between any and unknown type in TypeScript

Published: 2020.12.25 | 2 minutes read

Both any and unknown are universal types in TypeScript that allow you to assign whatever the heck you want to it.

let exampleAny: any;
let exampleUnknown: unknown;

// I can assign anything to `any` type
exampleAny = {}
exampleAny = 123;

// I can also assign anything to `unknown` type
exampleUnknown = {}
exampleUnknown = 123;

So you may be asking… what’s the difference between them? The difference is in accessing those values. Look!

let exampleAny: any;
let exampleUnknown: unknown;

// You can access Number.prototype method on any
// Without checking if the value is a number
console.log(exampleAny.toFixed());

// You can't access Number.prototype method on unknown
// Without checking if the value is a number
console.log(exampleUnknown.toFixed());
// ‼️ Error: Object is of type 'unknown'

Using any disables type-checking same as @ts-ignore does. The unknown is a type-safe counterpart of any type — before accessing the value, it requires type assertion or narrowing to a more specific type.

// Thats fine because before accesing Number.prototype method
// We can be assured that the type of value is a "number"
if (typeof exampleUnknown === "number") {
  console.log(exampleUnknown.toFixed());
}

Rule of thumb for any and unknown type #

Use any type only during the migration from JavaScript to TypeScript codebase, unknown otherwise. Karma will catch you if you assign an any type just because you can’t bothered to define meaningful type!

If you liked this article, please share it on Twitter.

Copyright © 2020 Pawel Grzybek

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK