Extract for Type-Safe Subsets
What you'll learn: How to use Extract<T, U> to pull out specific types from a larger union, creating safe, focused subsets.
The Core Idea
While Exclude removes types from a union, Extract does the opposite—it keeps only the types that match. Think of it like a filter that lets through only what you're looking for.
If you have a union of many types and need to work with just a specific subset, Extract gives you a type-safe way to select exactly what you need.
Syntax
type Result = Extract<UnionType, TypeToMatch>;
Extract compares each member of UnionType against TypeToMatch. Any member that extends (is assignable to) TypeToMatch gets included in the result.
Creating Type-Safe Subsets
type Status = "pending" | "success" | "error" | "loading";
// Extract only the "good" states
type SuccessStates = Extract<Status, "success" | "loading">;
// Result: "success" | "loading"
This is powerful when you want to narrow down what values are acceptable in specific contexts:
type Event =
| { type: "click"; x: number; y: number }
| { type: "keypress"; key: string }
| { type: "scroll"; delta: number }
| { type: "focus" };
// Extract only mouse-related events
type MouseEvent = Extract<Event, { type: "click" }>;
// Result: { type: "click"; x: number; y: number }
Key Takeaway: Extract<T, U> lets you safely pull matching types from a union, ensuring you work only with the subset you need—perfect for filtering states, events, or discriminated union variants.