首页 > 解决方案 > Typescript将两种数据类型数组合二为一

问题描述

如何使用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

标签: javascriptarraystypescripttypes

解决方案


我认为这与.concat()Typescript 中的实现有关。它被实现为合并数组的类型预计是foo这里的类型。这就是它抛出错误的原因。

您可以在此处从 Typescript Playground检查代码片段的错误选项卡,以了解更多信息。

如果你想让它工作,你可以使用扩展运算符。它应该可以正常工作。

const foo: string[] = ['hello', 'world'];
const bar: number[] = [1, 2];
const both: (string | number)[] = [...foo, ...bar]; 

推荐阅读