Conditional Types for Discriminated Union Helpers
What you'll learn: How to use conditional types to extract specific variants from a discriminated union by pattern-matching on their discriminant property.
The Core Problem
When working with discriminated unions, you often need to extract just one variant from the entire union. For example, if you have a union of different event types, you might want a helper type that gives you only the "success" events, or only the "error" events. Conditional types let you filter unions by checking their discriminant property.
How It Works
Conditional types distribute over unions, meaning they check each member individually. You can use this to build a filter: "give me all union members where the discriminant property matches this literal type."
Here's the pattern:
type Action =
| { type: 'loading' }
| { type: 'success'; data: string }
| { type: 'error'; message: string };
// Extract only actions where type is 'success'
type ExtractByType<Union, Type> = Union extends { type: Type }
? Union
: never;
type SuccessAction = ExtractByType<Action, 'success'>;
// Result: { type: 'success'; data: string }
type ErrorAction = ExtractByType<Action, 'error'>;
// Result: { type: 'error'; message: string }
The conditional type checks each union member. When Union is { type: 'success'; data: string }, the condition extends { type: 'success' } is true, so we keep it. For other members, the condition fails and we return never, which gets filtered out of the union.
Practical Application
This pattern is invaluable for creating type-safe handlers:
function handleSuccess(action: ExtractByType<Action, 'success'>) {
console.log(action.data); // TypeScript knows 'data' exists
}
Key Takeaway: Conditional types can filter discriminated unions by matching on discriminant properties, giving you precise type-safe subsets of your union variants without manual repetition.