Combining Exclude with Discriminated Unions
What you'll learn: How to surgically remove specific variants from a discriminated union using Exclude<T, U>.
The Core Idea
You've already seen discriminated unions (unions where each variant has a unique tag property) and Exclude<T, U> (which filters out specific types from a union). When you combine them, you get a powerful pattern: filtering out entire variants based on their discriminant property.
This is incredibly useful when you want to create a "narrower" version of a union that doesn't include certain cases—like filtering out error states, removing deprecated variants, or creating subsets of actions for specific handlers.
How It Works
The trick is to exclude based on the discriminant property's literal type:
type Result =
| { status: 'success'; data: string }
| { status: 'error'; message: string }
| { status: 'loading' };
// Remove the 'loading' case
type SettledResult = Exclude<Result, { status: 'loading' }>;
// Result: { status: 'success'; data: string } | { status: 'error'; message: string }
TypeScript matches the shape { status: 'loading' } against each union member and removes exact matches.
You can exclude multiple variants:
type SuccessOnly = Exclude<Result, { status: 'error' } | { status: 'loading' }>;
// Result: { status: 'success'; data: string }
This pattern is extremely common when processing discriminated unions where only certain states are valid for a given operation—like handling only settled promises, or processing only successful API responses.
Key Takeaway: Exclude lets you filter discriminated unions by matching on discriminant properties, creating type-safe subsets without manually redefining the union.