Discriminated unions (tagged unions) use a common property to distinguish between variants, enabling exhaustive type checking.
Basic Discriminated Union#
Exhaustiveness Checking#
API Response Patterns#
State Machine Pattern#
Action Types (Redux-style)#
Validation Results#
Nullable Patterns#
Event System#
Combining with Generics#
Best Practices#
Conclusion#
Discriminated unions provide type-safe handling of multiple variants using a common discriminant property. They're perfect for state machines, API responses, Redux actions, and any scenario with mutually exclusive states. Use exhaustiveness checking with never to catch unhandled cases. The pattern integrates well with TypeScript's type narrowing, giving you precise types within each branch of your conditional logic.