What is the best way to concatenate two arrays in typescript when they are ReadonlyArray
s? Take a look at the following example:
const strings1: ReadonlyArray<string> = ["foo"];
const strings2: ReadonlyArray<string> = ["bar"];
const allStrings = strings1.concat(strings2);
When attempting to do this, I encountered a compile error related to the strings2
parameter in the concat
method:
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>'.
Looking at the typings for concat
on ReadonlyArray
, it makes sense:
concat(...items: (T | T[])[]): T[];
However, it seems like there should be a more straightforward way to concatenate two ReadonlyArray
s. Am I overlooking something, or is there a simple solution that I am missing?
Possible solutions include:
- Extend the typings of
ReadonlyArray
to include the desired definition - Cast the
ReadonlyArray
to a regular array:strings1.concat(strings2 as string[])
- Create a new regular array before concatenating:
strings1.concat([].concat(strings2))
I am currently using Typescript 2.4.2.