为什么Typescript的人要创建infer
关键字?
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
我不明白为什么需要这个.为什么不能是:
type ReturnType<T> = T extends (...args: any[]) => R ? R : any;
为什么这不管用?为什么infer
关键字是必要的?
为什么Typescript的人要创建infer
关键字?
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
我不明白为什么需要这个.为什么不能是:
type ReturnType<T> = T extends (...args: any[]) => R ? R : any;
为什么这不管用?为什么infer
关键字是必要的?
对于infer
,编译器确保您已经声明了所有类型变量explicitly:
type MyType<T> = T extends infer R ? R : never;
type T1 = MyType<{b: string}> // T1 is { b: string; }
Here we declare a new type variable R
in MyType
, which gets inferred from T
.
(Note, that infer
is always used within the extends
clause of a conditional type.)
现在可以在未声明的结果中编译类型参数的用法:
type MyType2<T> = T extends R2 ? R2 : never; // error, R2 undeclared
如果没有infer
,编译器将不知道您是否想引入一个要推断的额外类型变量R2
(参见第一种情况),或者R2
是否只是一个意外的键入错误/打字错误.infer
的存在消除了这种模糊性.
更准确地说,如果省略infer
,编译器将判断T
is assignable到R
:
type R = { a: number }
type MyType3<T> = T extends R ? R : never; // compare T with type R
type T2 = MyType2<{b: string}> // T2 is never
请注意,infer R
个相同名称的类型声明的类型引用R
:
type R = { a: number }
type MyType<T> = T extends infer R ? R : never;
type T1 = MyType<{b: string}> // { b: string; }