Skip to content
TypeScript·Advanced·Coding·1 min read

What is exhaustive narrowing with never?

Short interview answer

After handling every member of a discriminated union, the remaining value has type never. Assigning it to a never variable in the default branch makes the compiler report a missing case when the union expands.

Example

TypeScript
function area(s: Shape) {  switch (s.kind) {    case 'circle': return Math.PI * s.r ** 2;    case 'square': return s.side ** 2;    default: {      const _exhaustive: never = s; // errors if a new Shape is added      return _exhaustive;    }  }}

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Type narrowing

Related questions