patterntypescriptnoneModerate
Conditional Types and the infer Keyword
Viewed 0 times
TypeScript 2.8+
inferconditional typetype extractionReturnTypeParameters
Error Messages
Problem
You need to extract a type from inside another type (e.g., the resolved type of a Promise, the return type of a function) without hardcoding it.
Solution
Use 'infer' inside a conditional type to capture and name a type variable.
// Extract Promise value type
type Awaited<T> = T extends Promise<infer V> ? V : T;
type R = Awaited<Promise<string>>; // string
// Extract function parameters
type Params<T> = T extends (...args: infer P) => any ? P : never;
type P = Params<(a: string, b: number) => void>; // [string, number]
// Extract array element type
type Element<T> = T extends (infer E)[] ? E : never;
type E = Element<User[]>; // User
// Recursive unwrapping
type DeepAwaited<T> = T extends Promise<infer V>
? DeepAwaited<V>
: T;Why
'infer' introduces a type variable scoped to the true branch of a conditional type. TypeScript pattern-matches against the extends clause and binds the inferred type to the variable.
Gotchas
- 'infer' can only appear in the extends clause of a conditional type, not elsewhere.
- When the conditional is distributed over a union, 'infer' is resolved independently per union member.
- Circular recursive conditional types require the 'extends' check to eventually reach a base case.
Revisions (0)
No revisions yet.