【问题标题】:How to concat two ReadonlyArrays in Typescript?如何在 Typescript 中连接两个只读数组?
【发布时间】:2018-01-15 09:40:49
【问题描述】:

当它们是ReadonlyArrays 时,在打字稿中连接两个数组的推荐方法是什么?考虑以下几点:

const strings1: ReadonlyArray<string> = ["foo"];
const strings2: ReadonlyArray<string> = ["bar"];

const allStrings = strings1.concat(strings2);

在这种情况下,我在concat 方法的strings2 参数中遇到编译错误:

TS2345: Argument of type 'ReadonlyArray<string>' is not assignable to parameter of type 'string | string[]'. Type 'ReadonlyArray<string>' is not assignable to type 'string[]'. Property '[Symbol.unscopables]' is missing in type 'ReadonlyArray<string>'.

如果我在ReadonlyArray 上查看concat 的类型,这会有些道理:

concat(...items: (T | T[])[]): T[];

这感觉像是一种疏忽,因为当您使用 ReadonlyArrays 时,连接两个 ReadonlyArrays 似乎很常见。我是否遗漏了某些东西,或者我是否遗漏了一个明显的解决方案?

我看到的解决方案是:

  1. 扩展ReadonlyArray typings 以添加我想要的定义
  2. 将我的ReadonlyArray 转换为普通数组:strings1.concat(strings2 as string[])
  3. 在连接之前先创建一个新的普通数组:strings1.concat([].concat(strings2))

我正在使用 Typescript 2.4.2。

【问题讨论】:

    标签: arrays typescript typescript2.0


    【解决方案1】:

    已在 Typescript 2.5.1 中修复,请参阅 https://github.com/Microsoft/TypeScript/issues/17076

    【讨论】:

      【解决方案2】:

      使用扩展运算符:

      const strings1: ReadonlyArray<string> = ["foo"];
      const strings2: ReadonlyArray<string> = ["bar"];
      
      const allStrings = [...strings1, ...strings2];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-09
        • 2010-12-14
        • 2020-02-24
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多