Advertisement
Intermediate TypeScript, Discriminated Unions & Exhaustiveness Checking

What is exhaustiveness checking, and how does the 'never' type enable it in a default case?

Short answer

Exhaustiveness checking uses the fact that after handling every known variant, the remaining type should be 'never' (impossible) — assigning the narrowed value to a variable typed as never in a default/else branch causes a compile error if a new variant is ever added and…

Save TypeScript mock interview
Advertisement
AModel answer
Exhaustiveness checking uses the fact that after handling every known variant, the remaining type should be 'never' (impossible) — assigning the narrowed value to a variable typed as never in a default/else branch causes a compile error if a new variant is ever added and forgotten, catching incomplete handling at compile time.
function assertNever(x: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(x)}`);
}
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 here if a case is missing
  }
}
Real-world example
Guaranteeing that adding a new Shape variant later forces every switch statement handling shapes to be updated, caught by the compiler.
Likely follow-ups
  • What error message would you see if you added a Triangle variant but forgot to handle it?
Related topics