Course contentsShow
← TypeScript
Lesson 1460 of 1,79633. Inference Inversion PatternsFree lesson

Extracting Union Members Matching Conditions

Combine Extract utility with custom conditions to filter and extract specific union members.

Extracting Union Members Matching Conditions

What you'll learn: How to combine the Extract utility with custom conditions to filter and extract specific union members based on complex criteria.

The Core Idea

You already know that Extract<T, U> pulls out union members that match a simple type. But what if you need more sophisticated filtering—like "all function types" or "all objects with a specific property"? By combining Extract with conditional types and infer, you can build powerful type-level filters that act like Array.filter but for unions.

Building Conditional Extractors

The pattern is straightforward: use Extract with a conditional type as the condition:

type ExtractFunctions<T> = Extract<T, (...args: any[]) => any>;

type Mixed = string | number | (() => void) | ((x: number) => string);
type OnlyFunctions = ExtractFunctions<Mixed>;
// Result: (() => void) | ((x: number) => string)

Extracting by Shape

You can extract union members that match a specific object shape:

type ExtractWithId<T> = Extract<T, { id: unknown }>;

type Entities = 
  | { id: string; name: string }
  | { value: number }
  | { id: number; age: number };

type WithId = ExtractWithId<Entities>;
// Result: { id: string; name: string } | { id: number; age: number }

Combining Multiple Conditions

Layer Extract calls or use intersection types in the condition:

type ExtractStringOrNumber<T> = Extract<T, string | number>;

type Values = string | boolean | number | null;
type Primitives = ExtractStringOrNumber<Values>;
// Result: string | number

Real-World Pattern: Event Filtering

type Events =
  | { type: 'click'; x: number; y: number }
  | { type: 'keypress'; key: string }
  | { type: 'scroll'; delta: number };

type ExtractEventByType<T, EventType extends string> = 
  Extract<T, { type: EventType }>;

type ClickEvent = ExtractEventByType<Events, 'click'>;
// Result: { type: 'click'; x: number; y: number }

Think of this like having a union of ingredients, and creating a type-level strainer that only lets through ingredients matching your recipe requirements—whether that's "all liquids," "all dairy," or "everything with protein."

Key Takeaway: By using Extract with conditional types and structural patterns, you can filter union members based on arbitrary conditions—not just exact type matches—enabling sophisticated type-level data querying.