Get in touch

Send an email to:
Or find me online at: Github, X

Typesafe exhaustive switch statements

To ensure that every variant of an union type is handled in a switch statement, we can leverage the never type. When the switch statement is exhaustive, the value within the default case will be of the never type. By passing it to a function that expects a never type parameter, the code will only compile when all possible cases are handled.

If the cases do not cover all possible values, the TypeScript compiler will display an error like this: Argument of type 'string' is not assignable to a parameter of type 'never'.

The following example will result in a compile-time error because it fails to handle the End variant of the Section union type:

type Section = 'Start' | 'Main' | 'End'

// Helper that only accepts a value of type never, for all other types it will throw
function assertUnreachable(value: never) {
  throw new Error(`Unreachable code: ${JSON.stringify(value)}`)

function renderSection(section: Section) {
  switch (section) {
    case 'Start':
      return 'start'
    case 'Main':
      return 'main'
      // TypeScript will show an error
  return ''

See also: The never type