Skip to content
TypeScript

infer Keyword

Extract types within conditional types.

By EZ4Code Team
inferconditional-type

Code

// Extract array element type
type ElementOf<T> = T extends (infer U)[] ? U : never;
type R1 = ElementOf<string[]>;  // string

// Extract function return type
type Return<T> = T extends (...args: any[]) => infer R ? R : never;
type R2 = Return<() => number>;  // number

// Extract function parameters
type Params<T> = T extends (...args: infer P) => any ? P : never;
type R3 = Params<(a: number, b: string) => void>;  // [number, string]

// Extract Promise value
type Await<T> = T extends Promise<infer U> ? U : T;
type R4 = Await<Promise<boolean>>;  // boolean

// Recursive extraction
type DeepAwait<T> = T extends Promise<infer U> ? DeepAwait<U> : T;

Explanation

infer captures and extracts type variables within conditional types.

More TypeScript Snippets