object-transforms

Extract<T, U>

Keeps only those members of union T that are assignable to U. The dual of Exclude, giving the set-intersection T ∩ U.

type Extract<T, U> = T extends U ? T : never

Usage patterns

Pattern Purpose
Extract<T, string> Pull only string members from a mixed union
Extract<Event, { type: 'click' }> Filter discriminated union by discriminant
Extract<keyof T, string> Restrict to string keys, dropping symbol/number keys
Extract<T, never> Always never

Examples

type All = 'a' | 'b' | 1 | 2;
type Numbers = Extract<All, number>;

Result: 1 | 2

type Event = { type: 'click'; x: number } | { type: 'key'; k: string };
type ClickEvent = Extract<Event, { type: 'click' }>;

Isolates one variant of a discriminated union

type StrKeys<T> = Extract<keyof T, string>;

Handy when iterating keys with Object.keys, which returns strings only

type X = Extract<'a' | 'b', 'c'>;

Result: never — no members match

Gotcha

Like Exclude, Extract distributes over union members; wrap in a tuple to suppress. Passing a non-union yields either T or never with no in-between.

Related utility types

← All TS utility types · TypeScript vs JavaScript · any vs unknown vs never