[英]Typescript function using generics and rest properties doesn't automatic collect all possible types
Please see this minimum code below.请参阅下面的最低代码。
function zip<T>(...arrs: T[][]): T[][] {
return arrs
}
zip([1,2,3], ['a', 'b', 'c'])
// Type 'string' is not assignable to type 'number'.ts(2322)
zip<number | string>([1,2,3], ['a', 'b', 'c'])
// Ok, but a little bit bother to me.
I created a function using generics
and rest
properties.我使用
generics
和rest
属性创建了一个函数。
When I directly use zip([1,2,3], ['a', 'b', 'c'])
, I expect that typescript automatically finds out I'm using number | string
当我直接使用
zip([1,2,3], ['a', 'b', 'c'])
,我希望打字稿会自动发现我正在使用number | string
number | string
type, is there any way to achieve this? number | string
类型,有什么方法可以实现吗?
Typescript sees the first parameter is number[]
and this fixes T
and then you get an error for the second. Typescript 看到第一个参数是
number[]
并且这修复了T
然后你会得到第二个错误。 While in theory T
could be inferred to string | number
虽然理论上
T
可以推断为string | number
string | number
I would argue the current behavior is usually a good thing, it is more likely infering unions would lead to unexpected errors in other places. string | number
我认为当前的行为通常是一件好事,它更可能infering工会将导致其他地方发生意外错误。
You can get the compiler to accept the call you want if you make the compiler consider all the arguments as a whole, not individually, using tuples in rest parameters:如果您让编译器将所有参数作为一个整体而不是单独考虑,在其余参数中使用元组,您可以让编译器接受您想要的调用:
function zip<T extends any[][]>(...arrs: T): (T[number][number])[][] {
return arrs
}
zip([1,2,3], ['a', 'b', 'c'])
T
will be a tuple type for the sample call ( [number[], string[]]
, so to get the item type we use T[number][number]
(which will be string | number
for the sample call), and the get back to the array of arrays using [][]
T
将是示例调用的元组类型( [number[], string[]]
,因此要获取项目类型,我们使用T[number][number]
(这将是示例调用的string | number
),并且使用[][]
返回数组数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.