Tips for combining two ReadonlyArrays in Typescript?

What is the best way to concatenate two arrays in typescript when they are ReadonlyArrays? 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 ReadonlyArrays. Am I overlooking something, or is there a simple solution that I am missing?

Possible solutions include:

  1. Extend the typings of ReadonlyArray to include the desired definition
  2. Cast the ReadonlyArray to a regular array:
    strings1.concat(strings2 as string[])
  3. Create a new regular array before concatenating:
    strings1.concat([].concat(strings2))

I am currently using Typescript 2.4.2.

Answer №1

To combine two arrays in JavaScript, utilize the spread operator:

const arr1: ReadonlyArray<number> = [1, 2, 3];
const arr2: ReadonlyArray<number> = [4, 5, 6];

const combinedArray = [...arr1, ...arr2];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript and Azure Functions to send FormData containing a file using Axios

I'm currently facing an issue with my Azure Function that handles file uploads to the endpoint. I am attempting to repost the files to another endpoint microservice using Axios, but I keep getting an error stating "source.on is not a function" when tr ...

An issue has occurred: Error - The specified NgModule is not a valid NgModule

Everything was working smoothly, but suddenly I encountered this error message while running ng serve. I haven't made any recent upgrades or changes to dependencies. Could someone please provide guidance on how to resolve this issue? ERROR in Error: ...

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

A guide to implementing previousState in React hooks with TypeScript

I am trying to grasp the concept of using previous state with react hooks in typescript. The code snippet provided below does function, however, it throws an error stating: Type 'number' is not assignable to type 'HTMLDivElement'. Whi ...

Accessing User Session with NextAuth in Application Router API Route

Utilizing NextAuth in conjunction with Next.js's App Router, I have established an API route within my /app/api directory. Despite my efforts, I am encountering difficulties retrieving the session associated with the incoming request. Below is the sn ...

I am facing an issue with my interface - the variable designed to store boolean values

Something unusual happened with Typescript - I assigned a string value to a boolean variable, but no error was generated. I purposely triggered an error in order to observe how Typescript would react, only to find that it did not produce the expected erro ...

What is the best way to connect a ref to a stateless component in React?

I need help creating a stateless component with an input element that can be validated by the parent component. In my code snippet below, I'm facing an issue where the input ref is not being assigned to the parent's private _emailAddress propert ...

Choose the object's property name using TypeScript through an interface

Consider a simplified code snippet like the following: interface MyBase { name: string; } interface MyInterface<T extends MyBase> { base: MyBase; age: number; property: "name" // should be: "string" but only p ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

The module named "jquery" has not been loaded in this context: _. Please use require() to load it

As I work on migrating my Javascript files to Typescript, I encountered an issue when trying to use the transpiled javascript file in an HTML page. The error message I received is as follows: https://requirejs.org/docs/errors.html#notloaded at makeError (r ...

In what scenarios would implementing the JS Switch case statement be more efficient than using numerous If/Else statements?

Greetings and thank you in advance for any help or guidance. I am currently developing a Space Battle game and I am curious to know if there is a way to utilize a JavaScript SWITCH case statement to streamline the numerous If/Else statements that are curr ...

Using TypeScript's conditional types for assigning types in React

I'm tasked with creating a component that can belong to two different types. Let's call them Type A = { a: SomeCustomType } Type B = { b: SomeOtherDifferentType } Based on my understanding, I can define the type of this component as function C ...

pull information from mongodb into angular

I am attempting to retrieve data from MongoDB, but I keep seeing [object] [object]. How can I transfer array data from MongoDB to Angular? Here is the code snippet: import { Component, OnInit } from '@angular/core'; import {HttpClient} from &quo ...

Bypass React Query execution when the parameter is null

I am facing an issue with a react query problem. I have a separate file containing all the queries: const useFetchApTableQuery = (date: string): UseQueryResult => { const axiosClient = axios.create() const fetchApTableQuery = async (): Promise<A ...

Experience Next.js 13 with Chakra UI where you can enjoy Dark Mode without the annoying White Screen Flash or FOUC (flash of unstyled content)

Upon refreshing the page in my Next.js 13 /app folder application using Chakra UI, I notice a few things: A momentary white flash appears before switching to the dark theme. The internationalization and font settings momentarily revert to default before l ...

The compiler is showing an error with code TS5023, indicating that the option 'strictTemplates' is not recognized

When trying to compile my Angular application (v10), I encountered the following error message. An unexpected issue has occurred: tsconfig.json:14:5 - error TS5023: Unknown compiler option 'strictTemplates'. 14 "strictTemplates": t ...

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...

Is the graphql codegen accurately generating the types?

I'm in the process of developing a basic Next.js application with TypeScript by integrating Strapi as a headless CMS. The main goal is to use Strapi and GraphQL, along with TypeScript, to display content on the Next.js app. Within Strapi, there is a ...

Deleting an item from a mongoDB array by specifying the index of the element in a dynamically defined array

Combining two questions: This query: Removing the array element in MongoDB based on position And this question: MongoDB set object where key value dynamically changes I am aware of dynamically defining fields (arrays) like this: { [arrayName]: { <con ...

PHP function in_array not verifying elements in the array

After importing words from a .txt file into an array using the file() function, I noticed that var_dump() showed the values as strings and print_r displayed them in a normal one-dimensional array format. $words = file('stopWords.txt'); //var_d ...