Skip to content
jshacks.dev
TypeScript

Check exhaustiveness with never

Assign the leftover value to a never variable in the default branch, and the compiler fails the build when you add a union member and forget a case.

1 min read
Summarize in AI

A switch over a union compiles even when you forget a case. Assigning the value to never in the default branch makes the forgetting a compile error.

shapes.tsTypeScript
type Shape =
  | { kind: 'circle'; r: number }
  | { kind: 'square'; side: number }
  | { kind: 'triangle'; base: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.r ** 2;
    case 'square':
      return shape.side ** 2;
    default: {
      const unreachable: never = shape;
      throw new Error(`unhandled shape ${JSON.stringify(unreachable)}`);
    }
  }
}
Text
shapes.ts(13,13): error TS2322: Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.

After the two case branches, TypeScript narrows shape to what is left, which is the triangle. A triangle cannot be assigned to never, so the line fails and the message names the case you missed. Add case 'triangle' and the leftover type becomes never, so the error disappears. See exhaustiveness checking.

Keep the throw. At runtime, data that skipped your types, such as a payload from a newer server, can still reach the default branch, and throwing is better than returning undefined.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.