0Pricing
TypeScript Academy · Lesson

Exhaustiveness Checking with never

Use never to ensure all union cases are handled.

Welcome

Exhaustiveness checking uses the `never` type to ensure every case of a union is handled. When you add a new union member, TypeScript will tell you exactly where to update your code.

The Exhaustiveness Problem

When you switch on a union type and forget a case, JavaScript silently falls through. TypeScript can detect this with a never check.
type Shape = 'circle' | 'square';
function area(s: Shape): number {
  if (s === 'circle') return 3.14;
  if (s === 'square') return 1;
  // What if we add 'triangle'?
}

All lessons in this course

  1. typeof and Truthiness Narrowing
  2. instanceof and in Narrowing
  3. User-Defined Type Guard Functions
  4. Exhaustiveness Checking with never
← Back to TypeScript Academy