为什么不将类型参数推断为联合类型?
Why isn't the type argument inferred as a union type?
此代码
declare function fn<T, U>(array: T[], predicates: ((arg: T) => U)[]): [T, U];
let a = fn([1, 2, 3], [x => 2, x => 's']);
导致此错误:
The type argument for type parameter 'U' cannot be inferred from the
usage. Consider specifying the type arguments explicitly. Type
argument candidate 'number' is not a valid type argument because it is
not a supertype of candidate 'string'. function fn(array: T[],
predicates: ((arg: T) => U)[]): [T, U]
这里为什么不能U
简单地推断出string | number
类型?
TypeScript 通常不会在泛型推理期间合成联合类型。简单来说,原因是不希望像这样进行推理:
function compare<T>(x: T, y: T): number { ... }
// Could infer T: string | number here... but that'd be bad
compare('oops', 42);
如果无法通过选择推理候选之一来形成通用类型,您将收到您发布的错误。
经验决定了这一选择。在以前的版本中(联合类型存在之前),如果没有推理候选者是所有候选者的超类型,则将推断出 {}
。在实践中,这导致 很多 遗漏错误,看起来像上面的例子。
此代码
declare function fn<T, U>(array: T[], predicates: ((arg: T) => U)[]): [T, U];
let a = fn([1, 2, 3], [x => 2, x => 's']);
导致此错误:
The type argument for type parameter 'U' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'number' is not a valid type argument because it is not a supertype of candidate 'string'. function fn(array: T[], predicates: ((arg: T) => U)[]): [T, U]
这里为什么不能U
简单地推断出string | number
类型?
TypeScript 通常不会在泛型推理期间合成联合类型。简单来说,原因是不希望像这样进行推理:
function compare<T>(x: T, y: T): number { ... }
// Could infer T: string | number here... but that'd be bad
compare('oops', 42);
如果无法通过选择推理候选之一来形成通用类型,您将收到您发布的错误。
经验决定了这一选择。在以前的版本中(联合类型存在之前),如果没有推理候选者是所有候选者的超类型,则将推断出 {}
。在实践中,这导致 很多 遗漏错误,看起来像上面的例子。