Exclude vs Extract Mental Model
You'll learn how to think about Exclude and Extract as mirror operations that filter type unions in opposite directions.
The Symmetrical Relationship
Exclude<T, U> and Extract<T, U> are complementary utilities that work on union types. They perform opposite filtering operations:
- Exclude removes types from
Tthat are assignable toU(keeps what doesn't match) - Extract keeps only types from
Tthat are assignable toU(keeps what does match)
Think of them like a sorting machine: given the same input union, Exclude throws away matches and keeps non-matches, while Extract keeps matches and throws away non-matches.
The Mental Model
Imagine a union type as a bag of colored balls. If you want balls that are not red or blue, use Exclude. If you want only red or blue balls, use Extract.
type Colors = "red" | "blue" | "green" | "yellow";
// Keep everything EXCEPT red and blue
type Warm = Exclude<Colors, "red" | "blue">; // "green" | "yellow"
// Keep ONLY red and blue
type Cool = Extract<Colors, "red" | "blue">; // "red" | "blue"
When to Use Each
Use Exclude when you know what you want to remove (blacklist approach):
- "Everything except error states"
- "All status codes except success codes"
Use Extract when you know what you want to keep (whitelist approach):
- "Only the string types from this union"
- "Only the success response types"
Key Takeaway: Exclude and Extract are symmetrical filters—Exclude removes matches, Extract keeps matches. Choose based on whether you're thinking in terms of what to remove or what to keep.