Understanding Exclude<T, U>
What You'll Learn
You'll learn how Exclude<T, U> removes specific types from a union by filtering out assignable members.
The Core Idea
Think of Exclude<T, U> as a filter for union types. Given a union T, it removes any type that could be assigned to U, leaving you with only the types that don't match.
It's like sorting a bag of mixed fruits and saying "give me everything except citrus" — you'd get apples, bananas, grapes, but no oranges or lemons.
How It Works
The syntax is simple:
type Result = Exclude<UnionType, TypeToRemove>;
TypeScript checks each member of the union T. If a member is assignable to U, it's filtered out. What remains forms your new type.
Basic Example
type Colors = "red" | "green" | "blue" | "yellow";
type PrimaryColors = Exclude<Colors, "green" | "yellow">;
// Result: "red" | "blue"
Here, "green" and "yellow" are removed from the union, leaving only "red" and "blue".
Excluding Primitive Types
type Mixed = string | number | boolean;
type OnlyNumbers = Exclude<Mixed, string | boolean>;
// Result: number
When to Use Exclude
Use Exclude when you need to derive a type by subtracting unwanted options from an existing union. It's perfect for creating restricted variants of broader types without rewriting everything.
Key Takeaway: Exclude<T, U> filters a union type T by removing any members that are assignable to U, giving you a cleaner, more specific type.