The unknown type
ℹ️ The 'unknown' type in TypeScript is the type-safe counterpart of 'any'. Unknown is assignable only to itself and any type. Unknown doesn't allow any operations without first asserting or narrowing.
unknown is the type-safe counterpart of any.
Anything is assignable to
unknown, butunknownisn’t assignable to anything but itself andanywithout a type assertion or a control flow based narrowing. Likewise, no operations are permitted on anunknownwithout first asserting or narrowing to a more specific type.
The easiest way to understand unknown is to compare it with any. As we know any type is used to opt-out of type checking. By using any type we can perform any action:
Just like all types are assignable to any, all types are assignable to unknown:
However, we can't simply perform any operations with our variable like it was with any type:
Additionally, we can't assign unknown type to any other types except itself and any:
Read more:
Last updated