【问题标题】:Typescript concat two data types array in oneTypescript将两种数据类型数组合二为一
【发布时间】:2021-10-19 04:39:59
【问题描述】:

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

【问题讨论】:

  • 请注意,数组数据结构本身应该只有一种类型的元素。您尝试创建的内容称为tupletuple 的每个元素的类型应预先输入。 const tuple:[string,number]=['str', 42]。此外,V8 更适用于同构数组

标签: javascript arrays typescript types


【解决方案1】:

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

您可以从Typescript Playground here 检查代码 sn-p 的错误选项卡以了解更多信息。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2011-02-12
    相关资源
    最近更新 更多