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

Extracting Generic Type Arguments

Capture type arguments passed to generic types using infer in conditional type patterns.

Extracting Generic Type Arguments

What you'll learn: How to capture and extract the type arguments that were passed to a generic type using infer in conditional type patterns.


The Problem

When you work with generic types like Promise<string> or Array<number>, TypeScript knows what those type arguments are. But what if you need to extract them? What if you have a Promise<T> and you need to pull out just the T?

This is where extraction through inference comes in.

How It Works

You can use infer within a conditional type to "pattern match" against a generic type and capture its type argument. The syntax looks like this:

type ExtractGenericArg<T> = T extends SomeGeneric<infer U> ? U : never;

Think of infer U as saying: "If T matches the shape SomeGeneric<something>, capture that something and call it U. Then I can use U in the true branch."

Practical Example: Extracting from Promise

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

type A = Unwrap<Promise<string>>;  // string
type B = Unwrap<Promise<number>>;  // number
type C = Unwrap<boolean>;           // boolean (no Promise, so returns T)

Here, infer U captures whatever type is inside the Promise. If T isn't a Promise at all, we fall back to returning T unchanged.

Extracting from Other Generics

This pattern works for any generic container:

// Extract element type from Array
type ElementType<T> = T extends Array<infer E> ? E : never;

type D = ElementType<string[]>;  // string
type E = ElementType<number[]>;  // number

The infer E captures the array element type when the pattern matches Array<something>.

Why This Matters

This technique is the foundation for utilities like Awaited, ReturnType (which extracts from function return position), and custom helpers that unwrap or transform nested generic types. You're essentially teaching TypeScript to "look inside" a type structure and pull out the pieces you care about.


Key Takeaway: Use infer in conditional type patterns to capture and extract the type arguments passed to generic types, enabling powerful type transformations and unwrapping operations.