Typescript 将两种数据类型数组合并为一个

mka*_*mid 2 javascript arrays types 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
Run Code Online (Sandbox Code Playgroud)

bha*_*waj 5

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

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

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

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