首页 > 解决方案 > 来自传播运算符的打字稿联合类型

问题描述

我有一个具有以下签名的函数:

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 而无需在泛型参数中明确指定它。

标签: typescriptgenericstypescript-generics

解决方案


T不被推断为联合是故意的;请参阅为什么不将类型参数推断为联合类型?,以及microsoft/TypeScript#19596microsoft/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

Playground 代码链接


推荐阅读