typescript - 为什么条件类型中的 "infer"会改变返回类型?

标签 typescript typescript-generics

我正在使用条件类型并偶然发现了这个问题:

import { FormGroup, FormControl, AbstractControl } from '@angular/forms';
type Foo = FormGroup<{ title: FormControl<string> }>
type Bar = FormGroup<{ title2: FormControl<string>; }>;

type Baz = Foo | Bar extends FormGroup<infer U> ? 'ok ' : 'nok'; // NOK
//   ^?
type Baz2 = Foo | Bar extends FormGroup ? 'ok ' : 'nok'; // OK
//   ^?

为什么 infer 的存在会改变这里的返回类型?

Playground

最佳答案

编译器通常应该能够推断 U。我还不确定根本问题是什么,但我追踪到以下内容:

推理失败,因为 FormGroup 包含返回类型中有条件方法

没有条件,推理工作正常。

type Foo = FormGroup<{ title: string }>
type Bar = FormGroup<{ title2: string }>;

export declare class FormGroup<TControl = any> {    
    fn1(arg: TControl): TControl
//  fn2(arg: TControl): 0 extends TControl ? true : false
}

type Baz = Foo | Bar extends FormGroup<infer U> ? true : false;
//   ^? type Baz = true

一旦我们在返回类型中引入条件,推理就会中断。

type Foo = FormGroup<{ title: string }>
type Bar = FormGroup<{ title2: string }>;

export declare class FormGroup<TControl = any> {    
    fn1(arg: TControl): TControl
    fn2(arg: TControl): 0 extends TControl ? true : false
}

type Baz = Foo | Bar extends FormGroup<infer U> ? true : false;
//   ^? type Baz = false

我可能会进一步调查这个问题。

可能相关:


Playground

关于typescript - 为什么条件类型中的 "infer"会改变返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74717049/

相关文章:

reactjs - 如何在 React with Typescript 中使用和指定 Generic Hooks?

typescript :枚举泛型类型作为函数的参数

javascript - 无法调用类型缺少调用签名的表达式...没有兼容的调用签名

javascript - 通过数组在 Angular 6 中引导多个模块

typescript - 为什么 Typescript 会忽略超出已知大小的元组内容?

javascript - 使用 create-react-app 创建应用程序时出现 React 和 Bootstrap4 问题

typescript - 在函数定义本身中指定参数字典键的类型

typescript - 接受特定类型对象的 keyof 吗?

TypeScript 函数参数泛型

typescript - 获取通过另一个字段指定的泛型属性值的类型