DEV Community


Posted on • Updated on


Typescript: unknown vs any

Do you know the difference between unknown and any in typescript ? Do you know when is it useful to use unknown or any ? Do you know why using any is not recommended ? Well, here's a explanation of the differences and uses.

The type any was added to typescript to allow easy migration of the code for any javascript project. any and unknown are mostly the same with a key difference:

unknown does not allow access to any property on an object or variable or use any primitive methods. This is useful when you either don't know the shape of data you are dealing with or are migrating from legacy javascript code.

For example:

const a: any = '123';
Enter fullscreen mode Exit fullscreen mode

Doing this will result in a runtime error:

Image description

Now lets change the any to unknown and see what happens

const a: unknown = '123';
Enter fullscreen mode Exit fullscreen mode

Doing this with an unknown type will raise a compiler error.

Image description

To fix the above, we have to narrow the type (using truthiness narrowing) to a number using a type guard like:

const a: unknown = 123;
if (typeof a === 'number') {
Enter fullscreen mode Exit fullscreen mode

In short, benefits of using unknown are:

  • Leads us to use type narrowing ( article on this coming soon )
  • Refactoring legacy javascript code to typescript
  • Catch bugs early in the development cycle
  • Preventing runtime bugs in applications

See a short video that explains this in details.

Hope you find this useful.

We will discuss type narrowing, type assertion and type guards in the next few posts.

Until them, stay safe, stay healthy.

Top comments (0)