在条件类型中推断类型后返回该类型的意义何在?
关于TypeScript中
T extends infer R ? R : never的疑问 背景
我查阅了两篇Stack Overflow帖子,一篇探讨TypeScript中“非此即彼但不同时存在”的属性,另一篇是相关的长篇解答,这激发了我深入理解条件类型(conditional types)、分布式条件类型(distributive conditional types)和infer关键字的兴趣。
我还查看了三篇与infer关键字相关的帖子:
- 为什么TypeScript需要infer关键字?
- TypeScript中
T extends infer P里的P是什么上下文?不清楚P的来源 - 尝试理解
T extends infer U的局限性
我的当前理解
- 条件类型用于根据特定条件灵活调整预期返回类型。例如,如果变量属于
number类型则返回1,否则返回'string'。 infer用于告知编译器“尽可能推断该变量的类型”。
核心疑问
那么,编写如下类型定义的意义和适用场景是什么?
type GenericType<T> = T extends infer R ? R : never;
基于我查阅的三篇帖子,我认为这种写法确实有用/必要(而非仅用于示例)。
我能理解它本质上是告知编译器“确认泛型类型T符合类型R,若符合则返回R,否则返回never”。但由于R是从T推断而来,且R处于条件类型的作用域内,它是否会与T有所不同?该条件难道不会始终为true吗?
在实际使用中,我未发现以下类型定义存在功能差异:
type GenericType1<T> = T extends infer R ? R : never; type GenericType2<T> = T extends T ? T : never; type GenericType3<T> = T; type FooBar = {a: 'foo', b: 'bar'}; const Example1: GenericType1<FooBar> = {a: 'foo', b: 'bar'}; const Example2: GenericType2<FooBar> = {a: 'foo', b: 'bar'}; const Example3: GenericType3<FooBar> = {a: 'foo', b: 'bar'}; const Example4: FooBar = {a: 'foo', b: 'bar'};
内容的提问来源于stack exchange,提问作者Torc
相关产品推荐
相关产品推荐

