What is the recommended way of concating two arrays in typescript when they are ReadonlyArray
s? Consider the following:
const strings1: ReadonlyArray<string> = ["foo"];
const strings2: ReadonlyArray<string> = ["bar"];
const allStrings = strings1.concat(strings2);
In this case I get a compile error in the strings2
parameter for 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>'.
And this makes some sense if I look at the typings for concat
on ReadonlyArray
:
concat(...items: (T | T[])[]): T[];
This feels like an oversight, because concating two ReadonlyArray
s seems like a common thing to do when you are using ReadonlyArray
s. Am I missing something, or is there an obvious solution I am missing?
Solutions that I see are:
ReadonlyArray
typings to add the definition I wantReadonlyArray
to an ordinary array: strings1.concat(strings2 as string[])
strings1.concat([].concat(strings2))
I am using Typescript 2.4.2.
Use the spread operator:
const strings1: ReadonlyArray<string> = ["foo"];
const strings2: ReadonlyArray<string> = ["bar"];
const allStrings = [...strings1, ...strings2];
Fixed in Typescript 2.5.1, see https://github.com/Microsoft/TypeScript/issues/17076
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With