Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 499
TomPeters Avatar asked Aug 08 '17 01:08

TomPeters


2 Answers

Use the spread operator:

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

const allStrings = [...strings1, ...strings2];
like image 129
Robby Cornelissen Avatar answered Oct 08 '22 21:10

Robby Cornelissen


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

like image 38
vbraun Avatar answered Oct 08 '22 19:10

vbraun