我有以下代码。
type Bar<A> = { f: A };
type Result<A> = { r: A };
function foo<A>(
f: (o: A, b: A extends object ? Bar<A> : undefined) => Result<A>
) {
return undefined as any;
}
const func = <A extends object>(b: Bar<A>) => {
return foo<A>((o: A, typeError: Bar<A>) => {
return undefined as any;
})
};
Run Code Online (Sandbox Code Playgroud)
我在名为 的参数的匿名函数中收到 (2) 个类型错误typeError。就它了type undefined/object is not assignable to type Bar<A>。我觉得这很奇怪,因为它A显然延伸了object,所以我们应该处于它不是undefined联盟的情况。
我认为编译器不会让您在包含泛型的条件类型上指定解析类型,即使它可以评估条件。
最简单的解决方法是指定相同的条件类型或让类型推断为您完成工作:
const func = <A extends Object>(b: Bar<A>) => {
return foo<A>((o: A, typeError: A extends Object ? Bar<A> : undefined) => {
typeError.f; // is ok
return undefined as any;
})
};
//Or
const func = <A extends Object>(b: Bar<A>) => {
return foo<A>((o: A, typeError) => {
typeError.f; // also ok
return undefined as any;
})
};
Run Code Online (Sandbox Code Playgroud)