Course contentsShow
← TypeScript
Lesson 804 of 1,79618. Conditional TypesFree lesson

infer for Nested Type Extraction

Chaining conditional types with infer to drill into deeply nested generic types like Promise<Array<T>>.

infer for Nested Type Extraction

You'll learn how to chain conditional types with infer to drill into deeply nested generic types and extract values buried inside structures like Promise<Array<T>>.

The Nesting Problem

Sometimes types are wrapped in multiple layers of generics. For example, an API might return Promise<Array<User>>. If you need to extract just the User type from this nested structure, a single infer won't cut it—you need to peel back multiple layers.

Chaining Conditional Types with infer

You can nest conditional types, using infer at each level to unwrap one layer at a time:

// Extract the resolved type from a Promise
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;

// Extract the element type from an Array
type UnwrapArray<T> = T extends Array<infer E> ? E : T;

// Chain them together to unwrap Promise<Array<T>>
type UnwrapPromiseArray<T> = UnwrapArray<UnwrapPromise<T>>;

type Result = UnwrapPromiseArray<Promise<Array<string>>>;
// Result = string

Single-Pass Deep Unwrapping

You can also nest the conditionals in a single type for deeper extraction:

type DeepUnwrap<T> = 
  T extends Promise<infer U>
    ? DeepUnwrap<U>  // Recursively unwrap promises
    : T extends Array<infer E>
      ? E  // Extract array element
      : T;  // Base case: return as-is

type MyType = DeepUnwrap<Promise<Promise<Array<number>>>>;
// MyType = number

This pattern recursively applies infer until it reaches the innermost type, allowing you to tunnel through arbitrary nesting depths.

Practical Use Cases

This technique is invaluable for utility types that work with async operations, API wrappers, or deeply nested data structures where you need type-level access to the core value.

Key Takeaway: Chaining conditional types with infer lets you drill through multiple generic wrappers like Promise<Array<T>>, extracting deeply nested types by peeling away one layer at a time.