Discriminated Unions for Safe Pattern Matching
Add a common literal field to union members for type safety.
Welcome
Discriminated unions add a shared literal property to union members. TypeScript uses this discriminant to narrow the type in switch and if statements.
The Discriminant Property
A discriminant is a property with a unique literal type in each union member. TypeScript narrows the union based on its value.
type Circle = { kind: 'circle'; radius: number };
type Square = { kind: 'square'; side: number };
type Shape = Circle | Square;All lessons in this course
- Union Types: A or B
- Intersection Types: A and B
- Discriminated Unions for Safe Pattern Matching
- Practical Patterns with Union and Intersection