Why use unknown
when we have any
in Typescript?
Type inferences are powerful and allows us to do magic when we don’t know types.
|
|
unknown
seems to do the same thing.
|
|
So, which to use where?
Let us extend the previous examples to put that question to rest. Consider what happens when you try to do any operation on the type.
|
|
unknown
applies itself enthusiastically to equality operations, asserts and checks, but not for any other operations.
This makes sense because we do not know the type of the particular variable and cannot subject it to operations or methods that expect a specific type.
Using unknown
lends itself to better type safety and is recommended to be used for unknown data types.