TypeScript: concat arrays with different element-types

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!

1 answer

  • answered 2018-01-13 17:17 Tsvetan Ganev

    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.