Typescript Special Types
As presented in Typescript: UI.dev
Any and Unknown
There are lots of circumstances where you don’t know the type of a variable, or the type signature is too complex to write.
You can use any or unknown in those circumstances.
any will allow any JS type, and effectively turns off type checking. We should avoid this if at all possible.
unknown is similar - represents any type - but limits what you can do on the value to preserve some type safety.
For example we can’t use a method on an unknown variable even if the value at the time has that method. We can really just pass the value around other unknown variables. We can’t even assign the value to a variable of its type.
So why is this helpful? We can use ‘type narrowing’ to prove that the value is a more specific type. So we could use the typeof
operator for example to narrow the type and persuade the TS compiler that the operation is safe.
Generally avoid any in favour of unknown where possible.
Interfaces