typescript - 来自传播运算符的打字稿联合类型
问题描述
我有一个具有以下签名的函数:
test<T>(...args: T[]): T
如果我这样调用函数:
const a = test(1, 2, 3)
一切都按预期工作(并且a
是 type number
),但是如果我这样称呼它:
const a = test(1, 2, "asd")
我收到任何错误:[EDIT] The 2 is red underlined: Argument of type '2' is not assignable to parameter of type '1'.
,witch 可能有点误导,因为参数是常量,但如果我这样称呼它:
let arg1 = 1;
let arg2 = "asd";
const a = test(arg1, arg2);
我得到错误:Argument of type 'string' is not assignable to parameter of type 'number'.
我怎样才能使函数(在第二种情况下)具有返回类型,number | string
而无需在泛型参数中明确指定它。
解决方案
T
不被推断为联合是故意的;请参阅为什么不将类型参数推断为联合类型?,以及microsoft/TypeScript#19596和microsoft/TypeScript#26746的原因。
解决这个问题的最简单方法可能是允许args
成为任何数组类型T
,然后通过使用键 type对其进行索引来number
获取其元素类型:
declare function test<T extends any[]>(...args: T): T[number];
const a = test(1, 2, 3) // number
const b = test(1, 2, "asd") // number | string
推荐阅读
- macos - 确保“从用户获取价值”对话框窗口始终位于 Robot Framework 的顶部
- c# - 如何使用 efCore 3 和 .net core 3 在程序中修复“方法‘ApplyServices’没有实现”
- reactjs - 使用酶获取 HTMLElement
- linux - 如何仅在 Docker 上下载 Git?
- linux - 找到匹配后如何替换一段代码 | Linux |
- angular - 父组件获取对 Angular 中任何子子组件的引用
- mongodb - MongoDB,查找属性 id 等于记录 id 的所有文档
- python - 如何使 Python 的功能可以查看导入的库
- java - 无法提取响应:没有找到适合响应类型类和内容类型 [text/html] 的 HttpMessageConverter
- mongodb - 将 MongoDB $max 结果转换为 golang 数据