打字稿将两种数据类型数组合二为一

姆卡姆兰哈米德

如何使用 .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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章