我正在使用条件类型并偶然发现了这个问题:
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
的存在会改变这里的返回类型?
最佳答案
编译器通常应该能够推断 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
我可能会进一步调查这个问题。
可能相关:
关于typescript - 为什么条件类型中的 "infer"会改变返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74717049/