什么是当他们是ReadonlyArray
s打字打字稿中两个数组的推荐方式?考虑以下几点:如何在打字稿中连接两个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>'.
这有一定的道理,如果我看分型为concat
on ReadonlyArray
:
concat(...items: (T | T[])[]): T[];
这感觉就像是一个疏忽,因为在使用ReadonlyArray
时,将两个ReadonlyArray
s拼接起来看起来很常见。我是否错过了一些东西,还是有一个明显的解决方案,我错过了?
的解决方案,我看到的是:
- 扩展
ReadonlyArray
分型加我想 - 投我
ReadonlyArray
一个普通数组的定义:strings1.concat(strings2 as string[])
- concating之前,首先创建一个新的普通阵列:
strings1.concat([].concat(strings2))
我正在使用Typescript 2.4.2。