javascript - Typescript concat two data types array in one - Stack Overflow

How do I concat two types array in one array using concat. If I initialize it with two data types it wo

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 the tuple 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
Add a ment  | 

1 Answer 1

Reset to default 6

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]; 

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744883392a4598974.html

相关推荐

  • javascript - Typescript concat two data types array in one - Stack Overflow

    How do I concat two types array in one array using concat. If I initialize it with two data types it wo

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信