0Pricing
TypeScript Academy · Lesson

Exhaustiveness Checking with never

Catch unhandled cases at compile time with never.

The Exhaustiveness Problem

When you add a new union member, it is easy to forget to handle it somewhere. Exhaustiveness checking turns that oversight into a compile error.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

// If we add "triangle" later, we want every switch to complain.

The never Type

The never type represents values that can never occur. If every case is handled, the value reaching the default branch has type never.

function fail(): never {
  throw new Error("unreachable");
}
// never is assignable to nothing except never itself.

All lessons in this course

  1. Building Discriminated Unions
  2. Narrowing on the Discriminant
  3. Exhaustiveness Checking with never
  4. Modeling State Machines
← Back to TypeScript Academy