Course contentsShow
← TypeScript
Lesson 973 of 1,79622. The never TypeFree lesson

Building Extract with never

How Extract leverages never in conditionals to keep only matching types from a union.

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:

  1. The conditional distributes over T if it's a union
  2. For each member in T, check if it extends U
  3. If yes, keep that member (T)
  4. If no, replace it with never
  5. Union all results — never disappears 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.