Docs
/
TypeScript
Chapter 15
15 — Discriminated Unions & Exhaustive Checks
Core Concepts
- Discriminated unions — union of objects sharing a literal discriminant field
- Switch narrowing —
switch(shape.kind)narrows to specific variant - Exhaustive checks —
nevertype ensures all cases handled - Pattern matching — type-safe branching on union members
- State machines — model application states with discriminated unions
Why Discriminated Unions
- The single most important pattern in TypeScript
- Models data that can be "one of several shapes"
- Compiler ensures you handle every case
- Eliminates impossible states by design