Skip to main content

TypeScript: Exhaustive Switch Helper

TypeScript

Make the compiler tell you when a union gains a case.

C
Chidi Okoro
Sample Sep 27, 2026
TypeScript · 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function assertNever(x: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(x)}`);
}

function label(status: 'todo' | 'doing' | 'done') {
  switch (status) {
    case 'todo': return 'To do';
    case 'doing': return 'In progress';
    case 'done': return 'Done';
    default: return assertNever(status);
  }
}
4 Fire 1 Learned something 2 Saved me time 0 Mind-blown
Sign in to react and star