TypeScriptBasic types

never

The type of a value that never occurs: functions that don’t end normally, and impossible cases.

On this page

Example

#
TypeScript
type Shape = { kind: 'circle'; r: number } | { kind: 'square'; side: number }

function assertNever(value: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(value)}`)
}

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.round(Math.PI * shape.r ** 2)
    case 'square':
      return shape.side ** 2
    default:
      return assertNever(shape)
  }
}

console.log(area({ kind: 'circle', r: 2 }))
console.log(area({ kind: 'square', side: 3 }))
Result
13
9

Definition and usage

#

The never type describes a situation that can’t happen. A function that returns never never ends with an ordinary return: it always throws an exception or runs in an infinite loop.

Its most practical use is checking exhaustiveness. If you handle every variant of a union in a switch, the value has the type never in the default branch. When someone adds a new variant and forgets to handle it, the compiler reports an error.

never also shows up on its own as the result of narrowing, once you’ve ruled out every possible type, and in conditional types as a way to “remove” a member of a union.

Syntax

#
Syntax
function fail(message: string): never {
  throw new Error(message)
}

Good practices

#
  • An assertNever function in the default branch is a simple way to make the compiler remind you about new variants.
  • Don’t use never as an “empty type” for variables. Nothing can be assigned to it.

Related entries

#

Spotted a mistake or missing an example? Write to us.