如何使用 .concat 将两种类型的数组连接到一个数组中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
我认为这与.concat()
Typescript 中的实现有关。它被实现为合并数组的类型预计是foo
这里的类型。这就是它抛出错误的原因。
您可以在此处查看 Typescript Playground 中代码片段的错误选项卡,以了解更多相关信息。
如果你想让它工作,你可以使用扩展运算符。它应该可以正常工作。
const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = [...foo, ...bar];
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句