Reputation: 12331
This is working.
let head = [["title", "value"], ["a", 1]];
let tail = [["b", 2], ["c", 3]];
let all = head.concat (tail);
The fine result is
[["title", "value"], ["a", 1], ["b", 2], ["c", 3]]
But what I need is this - and thats not working.
let head = [["title", "value"]];
let tail = [["a", 1], ["b", 2], ["c", 3]];
let all = head.concat (tail);
Error:
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'.
It works if I make the numbers in tail to strings - what I can not do because of reasons.
So how can I make it work??
Thanks!
Upvotes: 14
Views: 12598
Reputation: 3046
The recommended way to concat arrays these days is using es6 array spread. Type will be inferred correctly.
See MDN
const all = [...head, ...tail];
Upvotes: 19
Reputation: 8856
You can declare the type of head
like this:
let head: [Array<string|number>] = [["title", "value"]];
This will remove the error and keep the type-safety in place.
Upvotes: 9