any turns type checking off. unknown accepts any value but forces you to check it before use. never is the type that has no values at all.
any:
- You can assign anything to it, and assign it to anything.
- You can call it or read any property on it.
- So errors that TypeScript would catch slip through.
- It also spreads: values that come from an
anyare alsoany, so checking is lost further and further.
unknown is the safe top type. A top type is a type that every value fits into.
- You can assign anything to it.
- You cannot use it, or assign it to a typed variable, until you narrow it.
- You narrow it with
typeof,instanceof, a type guard or a validator. - It is the right type for
JSON.parseresults,catcherrors and other untrusted input.
never is the bottom type. A bottom type is a type that no value fits into. It appears in three places:
- the return type of functions that always throw or never finish
- the result of impossible intersections, like
string & number - what is left after every union case is narrowed away, which makes exhaustiveness checks possible
anyturns off type checking, and it spreads to every value that comes from it.unknownaccepts any value, but you must narrow it before you use it.- Use
unknownfor external or untrusted data, likeJSON.parseresults. neverhas no values. It is the type of throwing functions and impossible types.nevermakes exhaustiveness checks possible, because nothing is left after all cases are handled.
Read more