Lodash 中的 zip 功能打字稿错误

Rob*_*ith 2 typescript lodash

我想知道为什么 Typescript 会抱怨以下错误:

(22,28): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly.
  Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'number[]'.
Run Code Online (Sandbox Code Playgroud)

当我使用带有以下参数的 zip 函数时:

let ranges = ["0-100", "100-200", "200-300", "300-400", "400-500"];
let arrays = [[19.99, 49.99, 49.99, 49.99, 29.99, 29.99, 9.99, 29.99, 34.99, 34.99, 59.99], [149.99, 179.99, 129.99, 149.99, 129.99, 199.99, 129.99], [209.99, 249.99, 292.99, 279.99, 219.99]];

let result = _.zip(ranges, arrays);
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用 _.zipObject,错误就会消失。

如果这很重要,我使用typings install lodash --save.

更新 2

我认为zip不喜欢接收不同类型的参数。在这种情况下,ranges是 typestring[]arraystype number[]

更新

我错了。我改变了arrays使用字符串的值,但现在我得到了这个稍微不同的错误:

(24,28): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly.
  Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'string[]'.
Run Code Online (Sandbox Code Playgroud)

也许有一些与变量中的嵌套数组相关的东西arrays

Pac*_*ace 5

zip不喜欢不同类型的参数是正确的。如此处定义...

zip<T>(...arrays: List<T>[]): T[][];
Run Code Online (Sandbox Code Playgroud)

这基本上意味着所有参数必须是相同类型的数组。但是,当您将数组更改为字符串时,我怀疑您有类似...

let ranges = ["0-100", "100-200", "200-300", "300-400", "400-500"];
let arrays = [["19.99", "49.99",...], ["149.99", ...], ...];
Run Code Online (Sandbox Code Playgroud)

这些仍然不是同一类型。 ranges是一维字符串数组(数组string),数组是二维字符串数组(数组string[])。一组有效的输入将类似于...

let ranges = ["0-100", "100-200"];
let arrays = ["19.99", "49.99"];
Run Code Online (Sandbox Code Playgroud)

这里两种类型都是字符串数组。但是,我怀疑这不是您想要的。您想要的输出是否类似于以下内容?

[["0-100", ["19.99", ...]], ["100-200", ["149.99", ...]], ...]
Run Code Online (Sandbox Code Playgroud)

如果是这样,那么你可以简单地做......

_.zip<any>(ranges, arrays);
Run Code Online (Sandbox Code Playgroud)

这告诉打字稿强制T成为any这样函数定义变成......

zip(...arrays: List<any>[]): any[][];
Run Code Online (Sandbox Code Playgroud)

例子:

let ranges = ["0-100", "101-200"];
let arrays = [[0, 1, 2], [3, 4, 5]];
_.zip<any>(ranges, arrays);
//[ [ '0-100', [ 0, 1, 2 ] ], [ '101-200', [ 3, 4, 5 ] ] ]
Run Code Online (Sandbox Code Playgroud)

更新:正如评论中提到的,你也可以做......

_.zip<string|number[]>(ranges, arrays);
Run Code Online (Sandbox Code Playgroud)