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 inpatible.
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
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 inpatible.
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
Share
asked Aug 17, 2021 at 8:59
deathstrokedeathstroke
5937 silver badges19 bronze badges
1
-
Please be aware that array data structure itself should have only one type of elements. What you are trying to create called
tuple
. Type of each element of thetuple
should be typed upfront.const tuple:[string,number]=['str', 42]
. Furthermore V8 works better with homogeneous arrays – captain-yossarian from Ukraine Commented Aug 17, 2021 at 9:32
1 Answer
Reset to default 6I 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];
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744883392a4598974.html
评论列表(0条)