Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 397
chris01 Avatar asked Feb 02 '26 18:02

chris01


2 Answers

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

See MDN

const all = [...head, ...tail];
like image 58
sunn0 Avatar answered Feb 05 '26 08:02

sunn0


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.

like image 31
Tsvetan Ganev Avatar answered Feb 05 '26 07:02

Tsvetan Ganev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!