简体   繁体   English

使用泛型和其余属性的 Typescript 函数不会自动收集所有可能的类型

[英]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.我使用genericsrest属性创建了一个函数。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM