Discriminated Unions
Discriminated Unions
π¨βπΌ Discriminated unions (also called "tagged unions" or "algebraic data types")
are a pattern where each type in a union has a common "discriminant" property
with a literal type value.
type Circle = { kind: 'circle'; radius: number }
type Rectangle = { kind: 'rectangle'; width: number; height: number }
type Shape = Circle | Rectangle
The
kind property lets TypeScript narrow the type automatically. This is how
you make invalid states unrepresentableβthe type system ensures you can only
create valid combinations.π¨ Open
and:
- Create discriminated unions for API responses
- Create discriminated unions for payment methods
- Handle all cases with exhaustiveness checking


