如何在 Typescript 中连接两个只读数组?

How to concat two ReadonlyArrays in Typescript?

当两个数组为 ReadonlyArray 时,在打字稿中连接两个数组的推荐方法是什么?考虑以下因素:

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[];

这感觉像是一个疏忽,因为在使用 ReadonlyArray 时连接两个 ReadonlyArray 似乎是很常见的事情。我是否遗漏了什么,或者我是否遗漏了一个明显的解决方案?

我看到的解决方案是:

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

我正在使用 Typescript 2.4.2。

使用展开运算符:

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

const allStrings = [...strings1, ...strings2];

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