为什么类型参数不被推断为联合类型? [英] Why isn't the type argument inferred as a union type?

查看:29
本文介绍了为什么类型参数不被推断为联合类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

declare function fn<T, U>(array: T[], predicates: ((arg: T) => U)[]): [T, U];
let a = fn([1, 2, 3], [x => 2, x => 's']);

导致此错误:

类型参数 'U' 的类型参数不能从用法.考虑明确指定类型参数.类型参数候选 'number' 不是有效的类型参数,因为它是不是候选字符串"的超类型.函数 fn(数组: T[],谓词:((arg: T) => U)[]): [T, U]

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 |号码在这里?

Why can't be U simply inferred to have the type string | number here?

推荐答案

TypeScript 通常不会在泛型推理期间合成联合类型.简单来说,原因是不希望进行这样的推理:

TypeScript in general will not synthesize a union type during generic inference. The reason, in simplified terms, is that it's not desirable to do inference like this:

function compare<T>(x: T, y: T): number { ... }
// Could infer T: string | number here... but that'd be bad
compare('oops', 42);

如果无法通过选择推理候选之一形成泛型类型,您将收到您发布的错误.

If a generic type can't be formed by picking one of the inference candidates, you'll get the error you posted.

经验告诉了这个选择.在之前的版本中(在联合类型存在之前),如果没有推理候选是所有候选的超类型,则将推断 {}.在实践中,这导致了很多遗漏的错误,类似于上面的示例.

Experience informed this choice. In prior versions (before union types existed), {} would be inferred if no inference candidate was a supertype of all candidates. In practice this led to a lot of missed errors that looked like the example above.

这篇关于为什么类型参数不被推断为联合类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆