【发布时间】: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 似乎很常见。我是否遗漏了某些东西,或者我是否遗漏了一个明显的解决方案?
我看到的解决方案是:
- 扩展
ReadonlyArraytypings 以添加我想要的定义 - 将我的
ReadonlyArray转换为普通数组:strings1.concat(strings2 as string[]) - 在连接之前先创建一个新的普通数组:
strings1.concat([].concat(strings2))
我正在使用 Typescript 2.4.2。
【问题讨论】:
标签: arrays typescript typescript2.0