Skip to content
Advertisement

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!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement