Typescript concat two data types array in one



How do I concat two types array in one array using concat. If I initialize it with two data types it works fine but when I concat it. Typescript throws an error that both types are incompatible.

const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = foo.concat(bar); // gets an error on bar

const other: (string | number)[] = ['hello', 'world', 2, 3]; // this works

Answer

I think it has to do with the implementation of .concat() in Typescript. It is implemented as the type of the merged array is expected to be the type of foo here. That is the reason it is throwing an error.

You can check the error tab for your code snippet from Typescript Playground here to understand more about this.

If you want to make it work, you can use the spread operator. It should work fine.

const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = [...foo, ...bar]; 


Source: stackoverflow