Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

Exhaustive switch with a never check

Add a never check to a switch so TypeScript names any union member the switch leaves unhandled.

You added a triangle to a union of shapes and the build stayed green. The function that switches over the shapes now returns undefined for triangles, and nothing told you.

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number }
  | { kind: 'triangle'; base: number; height: number }

function area(shape: Shape) {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2
    case 'square':
      return shape.side ** 2
  }
}

const result: number = area({ kind: 'triangle', base: 3, height: 4 })
// error TS2322: Type 'number | undefined' is not assignable to type 'number'.

With strictNullChecks on, TypeScript infers number | undefined. The assignment fails for that reason. Enable noImplicitReturns to also flag the missing return at the function.

Make the switch complain

Pass shape to an assertNever function in default. TypeScript narrows it to the unhandled members there. When each member has a case that returns, the remaining type is never.

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.PI * shape.radius ** 2
    case 'square':
      return shape.side ** 2
    default:
      return assertNever(shape)
  }
}
// error TS2345: Argument of type '{ kind: "triangle"; base: number; height: number; }'
// is not assignable to parameter of type 'never'.

The error sits on the assertNever(shape) line inside the switch, and it prints the member you forgot. I ran it with Shape exported from its own file, and the error still landed in the file that holds the switch.

Annotating the return type as number on its own also fails, with TS2366: Function lacks ending return statement. That message does not say which case is missing.

Add the case

Add case 'triangle': return (shape.base * shape.height) / 2 above default and the error goes away. tsc reports nothing, and area returns 6 for a base of 3 and a height of 4.

An unexpected kind can still reach default at runtime if you cast unvalidated data to Shape. Validate JSON at the boundary and keep the throw as a backstop.

I keep assertNever in one shared file and import it. Each switch over a union then gets the same check with one line in default.