CodePark/ questions / any, unknown & never
START PRACTICINGPRACTICE
Frontend question · TypeScript › any, unknown & never

Explain the difference between any, unknown and never.

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 any are also any, 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.parse results, catch errors 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
  • any turns off type checking, and it spreads to every value that comes from it.
  • unknown accepts any value, but you must narrow it before you use it.
  • Use unknown for external or untrusted data, like JSON.parse results.
  • never has no values. It is the type of throwing functions and impossible types.
  • never makes exhaustiveness checks possible, because nothing is left after all cases are handled.