TypeScript Unknown Type

unknown type means that the type of variable is not known. It is the type-safe counterpart of any. We can assign anything to an unknown variable, but the unknown isn’t assignable to any other types except to unknown and any. To use an unknown type, we need to first assert its type or narrow it to a more specific type.

Unknown Type

Unknown type is a top type in TypeScript. You can assign anything to an unknown type.

You can assign unknown to a variable of type unknown and any.

But cannot assign unknown to any other types.

Type Assertion

You can use the Type Assertion on an unknown type to let the compiler know the correct type.

Narrowing the unknown Type

Another way is to narrow the types using type guards.

Unknown Vs Any

Both Any & Unknown data types are used when we do not know the Type.

Any Type

  1. You can assign anything to any type 
  2. You can perform any operation on any type

For Example, the following code does not throw any compiler errors. But this will result in run time errors. This is one of the major issues with using any type. This is why you should avoid using Any.

Unknown Type

  1. You can assign anything to unknown type
  2. You cannot perfom any operation on unknown type unless you perform a type check or type assertion

The above code with unknown type results in compiler error (Object is of type 'unknown'.).

The following code with the Any type does compile, but with Unknown type throws compile error.

You need to use the Typeof type guard to narrow the type to number to make it work without any issue. With this approach, you are sure not to get any run time errors. This is why the unknown type is recommended over Any type.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top