[英]Typescript concat two data types array in one
如何使用concat
在一个数组中连接两种类型的数组。 如果我用两种数据类型初始化它,它工作正常,但是当我concat
它时。 Typescript 抛出两种类型不兼容的错误。
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
我认为这与Typescript中.concat()
的实现有关。它的实现是因为合并数组的类型预计是这里的foo
类型。 这就是它抛出错误的原因。
您可以在此处查看来自 Typescript Playground的代码片段的错误选项卡,以了解更多相关信息。
如果你想让它工作,你可以使用扩展运算符。 它应该工作正常。
const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = [...foo, ...bar];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.