The parameter cannot be assigned the readonly type 'X' in this context

I encountered an issue with a third-party library where the class structure changed. Initially, it was defined as:

export class Foo {
  field: X[];
  ….
}

In my code, I was working with this type:

print(foo.field)

After updating to a new version, the class was updated to:

export class Foo {
  readonly foo: readonly X[];
  ….
}

This change caused my code to throw an error:

Argument of type 'readonly X' is not assignable to parameter of type 'X'.

Here is the function in question:

function print(foo: Foo[]): string {
  return //process foo, return some form of string
}

I am seeking guidance on how to resolve this error.

Answer №1

If you want to ensure that the array you pass to a function is not changed, you can specify it as readonly:

function display(data: readonly Data[]): string {
  return //process data and return a string
}

Using readonly type[] in TypeScript indicates that the array should remain unchanged. This restricts modifications by allowing only read-only operations on the array:

const dataArray: readonly number[] = [];
dataArray[0] = 5;
// Error: Index signature in type 'readonly number[]' only permits reading.
dataArray.push(10);
// Error: Property 'push' does not exist on type 'readonly number[]'.

readonly type[] is similar to ReadonlyArray<type>. More information can be found in the documentation on TypeScript's website.

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

Unexpected errors are encountered when using ng serve

When I run the ng serve command, unexpected errors are occurring on my system. The errors include: PS C:\Users\SAYED-SADAT\Desktop\data\coding\itsm-frontend\itsm-frontend> ng serveYour global Angular CLI version (13.0 ...

Numerous toggle classes available

Having the following HTML inside a <span> element: <span (click)="openLeft()"></span> A method in a @Component sets a boolean variable like so: private isOpen: boolean; openLeft() { this.isOpen = !this.isOpen; } To toggle classes ...

Change an ISO date format to DD:MM:YYYY HH:MM using Angular

I currently have my date in this format: 2022-11-21T21:07:56.830-07:00 However, I am looking to convert it to the following format: 21/11/2022 07:56 ...

Protractor Browser Instance Failure

We have encountered an issue with our UI suite failing in Chrome during the login process. Initially, we thought it might be due to upgrading to Chrome 79, as the problems arose simultaneously. Interestingly, the login functionality still works smoothly in ...

Converting a String variable to a String Literal Type in Typescript: A step-by-step guide

When working with Typescript, imagine I need to call a function that has the following signature- function foo(param: "TRUE"|"FALSE"|"NONE") Is there a way to achieve something like this- var str = runtimeString() if(str === "TRUE" | str === "FALSE" | s ...

I am encountering difficulties in accessing my component's property within the corresponding template while working with Angular 5

When I call an HTTP POST method to retrieve table names from the backend, I attempt to display them in the template using ngFor. However, the table names are not appearing on the screen. The tNames property is inaccessible in the template. As a beginner i ...

The importation of TypeScript source modules is not compiled accurately in the distribution folder

Currently, I am working on a REST API in TypeScript with the following structure: ├── dist │ ├── index.js │ ├── library.js ├── src │ ├── index.ts │ ├── library.ts ├── node_modules ├── package. ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

How to toggle visibility of multiple div elements in ReactJS

When working in react-js, I encountered a situation where two div elements and two buttons were used. Clicking the first button displayed the first div and hid the second div. Conversely, clicking the second button showed the second div and hid the first d ...

Explore the functionalities of RxJS filter operators by applying them to a stream of arrays

Is it possible to work with a stream of arrays, such as filtering, and then emit the arrays again without concatenating the elements of the arrays or using regular array operators? For example, if I have an observable containing a single array, I can perfo ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...

Ways to address the issue of duplicated names in input fields

Currently, I am utilizing a React Hook Form hook known as useFieldsArray. This hook is responsible for rendering an array of fields, each containing an object with the data that will be transmitted via the input. One interesting feature is the ability to ...

Developing an asynchronous function to retrieve data from an external API utilizing Await/Async strategy

Currently, there is a method under development that retrieves a value from the API. What steps are needed to properly integrate Async/Await functionality into this process? fetchAccountById(){ let accountName; this.accountService.fetchDa ...

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to this.projectService.projectState$ streams using methods like async or tap, the projectState$ e ...

Double up on your calls to the subscribe function in Angular to ensure successful login

Within my angular 7 application, there is a sign in component that triggers the sign in function within the authentication service. This function initiates an HTTP post request and then subscribes to the response. My goal is to have both the auth service f ...

getting TypeScript configured with webpack

I am currently using Typescript to develop a back-end API utilizing graphql and express. To manage the project development and building process, I have implemented webpack. As part of my setup, I am employing raw-loader in order to load graphql schemas an ...

Error: The script cannot be compiled with the '--isolatedModules' flag as it is recognized as a global script file

Currently, I am working on building my NextJS app and incorporating Cypress for testing along with Typescript. During this process, I encountered the following error: Type error: 'home.cy.ts' cannot be compiled under '--isolatedModules' ...

Using TypeScript with Node.js: the module is declaring a component locally, but it is not being exported

Within my nodeJS application, I have organized a models and seeders folder. One of the files within this structure is address.model.ts where I have defined the following schema: export {}; const mongoose = require('mongoose'); const addressS ...

Ways to turn off Typescript alerts for return statements

I'm looking to turn off this Typescript warning, as I'm developing scripts that might include return values outside of a function body: https://i.stack.imgur.com/beEyl.png For a better example, check out my github gist The compiled script will ...