AI Hints
Home›TypeScript Tutorial›Literal and Discriminated Unions
TypeScript · Lesson 36 of 120

Exhaustive Checks

Never miss a case.

⏱ 2 min read▶ Video at 28:18🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

What happens when someone adds a new payment kind, like gift cards? Every switch should handle it. An exhaustive check makes TypeScript tell you about any switch you forgot.

Exhaustive Checks
From the video: Exhaustive Checks
  • A new kind
  • Every switch
  • Don't forget one

Catching a missing case

We add a gift card kind, but the switch doesn't handle it yet. The default branch assigns the payment to never. Only a fully handled union is never. Run it. TypeScript points at the forgotten case.

app.tstypescript
type Payment =
  | { kind: "card"; last4: string }
  | { kind: "giftcard"; balance: number };

function describe(p: Payment): string {
  switch (p.kind) {
    case "card": return `Card ending ${p.last4}`;
    default: {
      const missed: never = p;
      return missed;
    }
  }
}
Output
app.ts line 9: Type '{ kind: "giftcard"; balance: number; }' is not assignable to type 'never'.

The pattern

Add a default branch that assigns the value to a variable of type never. While every case is handled, it compiles. The moment a case is missing, it doesn't.

keyvalue
defaultassign to never
All handledcompiles
One missingerror
Resultno forgotten cases

Summary

Assigning to never in the default branch makes switches exhaustive. Next, type guards.

Key takeaways
  • const x: never = p
  • Missing cases caught
  • Safe to extend
Next up: Type Guards — is