Extract for Pattern Matching
What you'll learn: How to use Extract to filter a union by matching structural patterns or shapes, not just literal types.
While we've seen Extract<T, U> pull out matching types from unions, its real power emerges when you use it to match by structure or shape. Instead of extracting a single named type, you can define a pattern and let Extract find all union members that fit it.
The Pattern Matching Idea
Think of Extract like a magnet that only attracts shapes with certain features. You describe what you're looking for (the pattern), and Extract finds every union member that matches that description.
type ApiResponse =
| { status: 'success'; data: string }
| { status: 'error'; message: string }
| { status: 'loading' }
| { status: 'idle' };
// Extract all responses that have a 'data' property
type ResponsesWithData = Extract<ApiResponse, { data: any }>;
// Result: { status: 'success'; data: string }
Here, we didn't name a specific type—we described a pattern: "any object with a data property." Extract found the match.
Matching by Shape
type Events =
| { type: 'click'; x: number; y: number }
| { type: 'keypress'; key: string }
| { type: 'scroll'; deltaY: number }
| { type: 'click'; button: 'left' | 'right' };
// Extract all events with coordinates
type CoordinateEvents = Extract<Events, { x: number }>;
// Both click event types match!
You can match partial shapes, and Extract finds all union members containing those properties with compatible types.
Key Takeaway: Extract is a pattern matcher—define a structural pattern with property shapes, and it filters the union to only members that satisfy that structure, enabling type-safe subset selection without naming every type explicitly.