When Discriminated Unions Shine
You'll learn where discriminated unions provide the cleanest, safest solutions in real-world code.
Now that you know how discriminated unions work, it's time to recognize the patterns where they truly excel.
Four Core Use Cases
1. Modeling Variants
When data can be "one of several shapes," discriminated unions are perfect. Think of API responses that vary by type, or UI components with different prop configurations:
type Button =
| { variant: 'primary'; label: string }
| { variant: 'icon'; icon: string }
| { variant: 'link'; href: string };
2. State Machines
Applications move through distinct states. Discriminated unions model this precisely:
type ConnectionState =
| { status: 'idle' }
| { status: 'connecting'; attempt: number }
| { status: 'connected'; sessionId: string }
| { status: 'error'; message: string };
Each state carries only the data relevant to that state—no nullable properties cluttering your type.
3. Result Types
Instead of throwing exceptions, return success or failure explicitly:
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
The caller must check success before accessing data—TypeScript enforces it.
4. Event-Driven Architectures
Events with different payloads? Discriminated unions make them type-safe:
type UserEvent =
| { type: 'login'; userId: string }
| { type: 'logout' }
| { type: 'update'; changes: object };
You get exhaustive checking on event handlers and autocomplete on event-specific properties.
Key Takeaway: Discriminated unions shine when modeling variants, state machines, result types, and event-driven systems—anywhere you have "one of these specific shapes" instead of "maybe all these nullable properties."