TomPeters
TomPeters

Reputation: 157

How to concat two ReadonlyArrays in Typescript?

What is the recommended way of concating two arrays in typescript when they are ReadonlyArrays? 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 ReadonlyArrays seems like a common thing to do when you are using ReadonlyArrays. Am I missing something, or is there an obvious solution I am missing?

Solutions that I see are:

  1. Extend ReadonlyArray typings to add the definition I want
  2. Cast my ReadonlyArray to an ordinary array: strings1.concat(strings2 as string[])
  3. Create a new ordinary array first before concating: strings1.concat([].concat(strings2))

I am using Typescript 2.4.2.

Upvotes: 11

Views: 5753

Answers (2)

vbraun
vbraun

Reputation: 1987

Fixed in Typescript 2.5.1, see https://github.com/Microsoft/TypeScript/issues/17076

Upvotes: 5

Robby Cornelissen
Robby Cornelissen

Reputation: 97247

Use the spread operator:

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

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

Upvotes: 12

Related Questions