Skip to content

Infer 推断

一句话解释

infer 在条件类型内声明类型变量,从匹配的模式中提取并捕获类型。

用大白话说

infer 关键字在 extends 条件类型内使用,从另一个类型中提取类型。它像类型级的模式匹配——你声明一个占位符,TypeScript 填充它。例如,type ElementOf<T> = T extends (infer E)[] ? E : never 提取数组的元素类型。如果 T 是 string[],infer E 捕获 string。常见用途:提取函数返回类型、Promise 解析类型、数组元素类型、组件属性类型。ReturnType<T> 工具类型就是用 infer 构建的。你可以有多个 infer 变量并在条件类型的 true 分支中使用它们。

示例

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

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

// Extract Promise resolution type
type Awaited<T> = T extends Promise<infer U> ? U : T;
type R3 = Awaited<Promise<string>>; // string

infer 从模式中捕获类型:从数组中 E,从函数返回中 R,从 Promise 中 U。TypeScript 填充推断的类型。

常见混淆

  • 容易混淆的对象: typeof

    关键区别: typeof 提取值的类型(运行时→类型)。infer 在条件类型内从另一个类型中提取类型(类型→类型)。typeof 作用于值;infer 作用于类型级条件逻辑内部。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表