为什么打字稿人会创建infer
关键字?根据documents,这是如何使用它的示例:
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
我不明白为什么需要这样做。为什么不能这样:
type ReturnType<T> = T extends (...args: any[]) => R ? R : any;
为什么不起作用?为什么infer
关键字是必需的?
请考虑以下代码:
interface Example {
foo: string
}
type GenericExample<T> = T extends Examlep ? 'foo' | 'bar';
此代码应该导致编译错误,因为Examlep
的拼写错误;没有名为Examlep
的类型,显然程序员打算在此处编写Example
。
现在想象一下,条件类型的infer
子句中不需要extends
关键字。那么上面的代码不会给出编译错误;它会看到没有名为Examlep
的类型,推断它是什么类型,然后(由于[C0]没有约束),观察到Examlep
确实为推断的类型扩展了T
。
在那种情况下,无论Examlep
是什么,GenericExample<T>
都会[[总是为'foo'
,并且不会有编译错误来通知程序员该错误。对于编译器来说,几乎所有的时间都是错误的。
使用T
,编译器将确保您已明确地
声明您要使用的所有类型变量:
infer
中的T
ReturnType<T> = ...
子句中-extends
中的R
infer R
,编译器将无法知道,是否真的想引入另一个要推断的类型变量(例如infer
),或者Foo
只是一个错字。