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

Nested infer for Deep Extraction

Chaining infer within nested conditional types to extract deeply nested type information from complex structures.

Nested infer for Deep Extraction

You'll learn how to chain infer within nested conditional types to extract deeply nested type information from complex structures.

When working with multi-layered types—like promises wrapped in arrays, or objects containing nested function types—a single infer isn't enough. You need to nest conditional types with multiple infer clauses, peeling away layers one at a time to reach the type buried deep inside.

The Core Idea

Think of nested structures like Russian nesting dolls. To get to the innermost doll, you must open each outer layer sequentially. Similarly, to extract a type from Promise<Array<User>>, you first unwrap the Promise, then unwrap the Array.

The technique chains conditional types:

type DeepExtract<T> = 
  T extends Promise<infer U> 
    ? U extends Array<infer V> 
      ? V 
      : U 
    : T;

type Result = DeepExtract<Promise<Array<string>>>;
// Result is string

Each infer captures one layer, and the next conditional dives deeper into that captured type.

Common Patterns

Unwrapping nested promises:

type UnwrapNestedPromise<T> = 
  T extends Promise<infer U>
    ? U extends Promise<infer V>
      ? UnwrapNestedPromise<V>
      : U
    : T;

type A = UnwrapNestedPromise<Promise<Promise<number>>>;
// A is number

Extracting deeply nested object properties:

type DeepProperty<T> = 
  T extends { data: infer D }
    ? D extends { user: infer U }
      ? U
      : D
    : never;

type Nested = { data: { user: { id: string } } };
type UserId = DeepProperty<Nested>;
// UserId is { id: string }

When to Use Nested infer

This pattern shines when working with API response wrappers, layered generic containers, or extracting metadata from complex function signatures. It's powerful but can hurt readability—use it when the type structure genuinely requires deep inspection.

Key Takeaway: Nested infer within chained conditional types lets you extract types from deeply nested structures by unwrapping one layer at a time, enabling sophisticated type transformations for complex data shapes.