Discriminated Union
Question
What is a discriminated union?
Hint
The discriminant property enables exhaustive switch checks.
Explanation
A discriminated union (tagged union) is a union of object types that share a common property with literal types (the discriminant). Example: type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number }. The kind property is the discriminant. TypeScript narrows the type when you check kind: if (shape.kind === "circle") narrows to the circle type. This enables exhaustive checking in switch statements. Discriminated unions are the idiomatic way to model variants in TypeScript.
Related Resources
Related Lessons
- Unions & Intersections
Learn unions/intersections.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.