TypeScript:具有不同元素类型的concat数组

时间:2018-01-13 17:06:25

标签: javascript arrays typescript

这很有效。

let head = [["title", "value"], ["a", 1]];
let tail = [["b", 2], ["c", 3]];

let all = head.concat (tail);

结果很好

[["title", "value"], ["a", 1], ["b", 2], ["c", 3]]

但我需要的是 - 而且那不起作用。

let head = [["title", "value"]];
let tail = [["a", 1], ["b", 2], ["c", 3]];

let all = head.concat (tail);

错误:

Argument of type '(string | number)[][]' is not assignable to parameter 
of type 'string[] | string[][]'. 
 Type '(string | number)[][]' is not assignable to type 'string[][]'. 
  Type '(string | number)[]' is not assignable to type 'string[]'. 
   Type 'string | number' is not assignable to type 'string'. 
    Type 'number' is not assignable to type 'string'.

如果我把尾巴中的数字变成字符串,那就有用了 - 因为原因,我不能这样做。

那我怎样才能让它发挥作用?

谢谢!

1 个答案:

答案 0 :(得分:4)

您可以像这样声明head的类型:

let head: [Array<string|number>] = [["title", "value"]];

这将消除错误并保持类型安全。