代码点读机 / TypeScript / infer

infer TypeScript · 关键字

在类型定义里临时"抓"出一个类型存到变量,像从快递箱标签上读取内件类型。

怎么用

type 名<T> = T extends ... ? infer X : never;

小例子

type 返回<T> = T extends () => infer R ? R : never;
type N = 返回<() => number>;

类型检查结果

N 是 number

提醒:只能在条件类型的 extends 分支里使用

官方文档:https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#inferring-within-conditional-types

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← TypeScript全部词条