TypeScript Fundamentals

`any`, `unknown` & `never`

any disables type checking, unknown means a value must be checked before use, and never represents impossible values or unreachable paths.
  • any opts out
  • unknown is safe uncertainty
  • never means impossible
  • Use unknown at boundaries
  • Use never to make missed cases fail loudly
The three escape/extreme types
TypeMeaningUse
anyCompiler, stop checking thisIsolated migration or unavoidable interop
unknownI do not know this yetUntrusted input
neverThis cannot happenExhaustiveness and unreachable code
Exhaustiveness with never
function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${JSON.stringify(value)}`)
}

function render(state: LoadState<User>) {
  switch (state.kind) {
    case "loading": return "Loading"
    case "success": return state.data.name
    case "error": return state.error.message
    default: return assertNever(state)
  }
}
Adding a new variant now forces this switch to be updated.
Sources
  • The TypeScript HandbookEveryday Types; Narrowing
  • Effective TypeScript, 2nd Editionany and unknown
  • TypeScript Referencenever