Nâng CaoTypeScript iconTypeScript

infer keyword trong conditional types là gì?

infer khai báo type variable trong conditional type để 'capture' type được infer.

Chỉ dùng trong extends clause.

typescript
// Extract return type của function
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type R = ReturnType<() => Promise<string>>; // Promise<string>

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

// Extract element type từ array
type UnwrapArray<T> = T extends (infer U)[] ? U : T;
type U = UnwrapArray<string[]>; // string

// Extract từ Promise
type Awaited<T> = T extends Promise<infer V> ? Awaited<V> : T;
type V = Awaited<Promise<Promise<number>>>; // number

Cho phép extract nested types từ complex types một cách type-safe.

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript