chris01
chris01

Reputation: 12331

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!

Upvotes: 14

Views: 12598

Answers (3)

sunn0
sunn0

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

ThorEpNorway
ThorEpNorway

Reputation: 105

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

Upvotes: 3

Tsvetan Ganev
Tsvetan Ganev

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

Related Questions