14

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!

3 Answers 3

20

The recommended way to concat arrays these days is using es6 array spread. Type will be inferred correctly.

See MDN

const all = [...head, ...tail];
Sign up to request clarification or add additional context in comments.

3 Comments

Please explain your answer furtehr
Surely you know how this works, it was flagged in review queues. :-)
Fyi, looking at some benchmarks, spread is slightly slower. Probably insignificant in 99% of cases but if you need high perf, take that into account.
9

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.

1 Comment

To narrow further let head: Array<[string, string|number]>
3

You can just do this: [].concat(head, tail)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.