chr*_*s01 11 javascript arrays typescript
这是有效的。
let head = [["title", "value"], ["a", 1]];
let tail = [["b", 2], ["c", 3]];
let all = head.concat (tail);
Run Code Online (Sandbox Code Playgroud)
好的结果是
[["title", "value"], ["a", 1], ["b", 2], ["c", 3]]
Run Code Online (Sandbox Code Playgroud)
但我需要的是这个 - 但那不起作用。
let head = [["title", "value"]];
let tail = [["a", 1], ["b", 2], ["c", 3]];
let all = head.concat (tail);
Run Code Online (Sandbox Code Playgroud)
错误:
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'.
Run Code Online (Sandbox Code Playgroud)
如果我将数字放在字符串尾部,它就会起作用 - 由于某些原因我不能这样做。
那么我怎样才能让它发挥作用呢?
谢谢!
sun*_*nn0 11
目前推荐的连接数组的方法是使用 es6 array spread。将正确推断类型。
参见MDN
const all = [...head, ...tail];
Run Code Online (Sandbox Code Playgroud)
您可以像这样声明类型head:
let head: [Array<string|number>] = [["title", "value"]];
Run Code Online (Sandbox Code Playgroud)
这将消除错误并保持类型安全。
| 归档时间: |
|
| 查看次数: |
9922 次 |
| 最近记录: |