Building Extract with never
You'll learn: How to implement TypeScript's Extract utility type using conditional types and never to filter unions.
The Core Idea
Extract<T, U> is a utility type that keeps only the members of union T that are assignable to U. It works by leveraging distributive conditional types and using never to eliminate unwanted types.
Here's the mental model: when a conditional type distributes over a union, each member is tested individually. If it passes the test (extends the target), keep it. If not, replace it with never — which vanishes from the union.
How Extract Works
type Extract<T, U> = T extends U ? T : never;
Let's break down what happens:
- The conditional distributes over
Tif it's a union - For each member in
T, check if it extendsU - If yes, keep that member (
T) - If no, replace it with
never - Union all results —
neverdisappears automatically
Practical Example
type Extract<T, U> = T extends U ? T : never;
type Mixed = string | number | boolean | null;
// Extract only string-compatible types
type OnlyStrings = Extract<Mixed, string>;
// Result: string
// Extract only number or boolean
type NumberOrBool = Extract<Mixed, number | boolean>;
// Result: number | boolean
// Extract falsy types
type Falsy = Extract<Mixed, false | null | 0 | "">;
// Result: null
The magic happens because each union member is tested independently, and failed matches become never, which the type system removes from the final union.
Why never Is Essential
Without never, you'd have no way to "remove" types from the result. Using undefined or any other type would pollute the final union. never is the only type that truly disappears from unions, making it perfect for type-level filtering.
Key Takeaway: Extract uses conditional types to test each union member against a pattern, keeping matches and replacing failures with never, which silently vanishes from the resulting union.