TypeScript theorytheory 0/50 · 0%
Control flow · medium

22. never and exhaustiveness checks

Using the empty type to catch missing switch cases.

`never` represents a value that can never occur — the return type of a function that always throws, or the type of a variable that has been narrowed to nothing.

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

type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };

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

If someone adds a new `Shape` variant but forgets a case, `shape` in the `default` branch will no longer be `never`, and passing it to `assertNever` produces a compile error — turning a missed-case bug into a build failure instead of a runtime surprise.

Check your understanding

  1. 1. What does the `never` type represent?

  2. 2. How does `assertNever(shape)` in a `default` case help?

  3. 3. What is the return type of a function that always throws?