Tips for declaring an immutable object parameter in a Typescript function

Can we prevent an object parameter from being modified in typescript, for example:

interface MyType {
   prop1: number
}

function myMethod(param: readonly MyType) {
   // How can we make TypeScript give an error here:
   param.prop1 = 2
}

Answer №1

To prevent any modifications to the properties of an object, you can utilize the type utility Readonly<Type> as shown below:

TS Playground

interface MyType {
  prop1: number;
  prop2: number;
}

function myMethod(param: Readonly<MyType>) {
  param.prop1 = 2; /*
        ~~~~~
  Cannot assign to 'prop1' because it is a read-only property.(2540) */

  param.prop2 = 1; /*
        ~~~~~
  Cannot assign to 'prop2' because it is a read-only property.(2540) */
}

If you only wish to restrict specific properties from being altered, you can label them as read-only using the readonly modifier:

TS Playground

interface MyType {
  readonly prop1: number;
  prop2: number;
}

function myMethod(param: MyType) {
  param.prop1 = 2; /*
        ~~~~~
  Cannot assign to 'prop1' because it is a read-only property.(2540) */

  param.prop2 = 1; // ok
}

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

React query useMutation error: Unable to execute logout function

I've encountered an issue while working with React Query's useMutation for a basic API call to log out a user. Despite having what appears to be correct code, I keep getting an error message from React indicating that onLogout is not a function. ...

Combining objects in JavaScript

I am currently working on converting the object received from the server into a format compatible with the backend system. I have a received object that looks like this { 'User.permissions.user.view.dashboard': true, 'Admin.permissio ...

Error: Attempting to access 'pageContext' property on undefined object, resulting in TypeError while utilizing sp pnp v3

I am currently following a tutorial to build a webpart using SPFX and SP/PNP v3: https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/use-sp-pnp-js-with-spfx-web-parts I have also consulted: Here is the main .ts file: public async onIn ...

In RxJS, the map operator takes the whole array as its parameter

implement constantA = (id: string): Observable<Array<any>>=>{ } improve constantB = (id: string): Observable<Array<myClass>>=>{ constantA(metroId).map((x)=>{ return new myClass( x.FacilityName, ...

What is the process for calling subjects dynamically in a service?

Do you have a service with the following subjects? subjectOne$ = new Subject<Partial<boolean>>(); subjectTwo$ = new Subject<Partial<boolean>>(); subjectThree$ = new Subject<Partial<boolean>>(); subjectFour$ = new ...

Is it possible for a TypeScript definition file to include a require statement?

Can I include a statement like this in my definition file (.d.ts)? import foo = require('some-module/bar'); I believed this would automatically convert my definition file into a module. Surprisingly, it still works for me even without strict mo ...

Error: The function 'some' is not recognized in the rawData variable in REACT/ANTDESIGN

I've been grappling with this issue for nearly a full day now. Despite exhausting all possible solutions and conducting extensive searches, I'm still stumped. My task is to create a table using ant design where all the users are displayed upon i ...

Exploring Angular 17's unique approach to structuring standalone components

Is something wrong with my code if I can only see the footer, header, and side-nav components on localhost? How can I fix this? app.component.html <div class="container-fluid"> <div class="row"> <div class=&q ...

Getting a 404 error despite the status code being properly set to 200 in the response

I have developed a NodeJS Express API using TypeScript. All API calls are returned through the following method: private setResponseWithStatusCode<TResult>( result: TResult, httpStatusCode: number, response: Response): Response { l ...

Tips for including an authorization token in an HTTP request

I encountered a 401 unauthorized error when trying to access my REST endpoint, likely due to the security measures I have implemented. I suspect that there might be an issue with how I am handling the HTTP headers. The application utilizes a Spring Boot b ...

Issue: The JSX element 'X' is missing any constructors or call signatures

While working on rendering data using a context provider, I encountered an error message stating "JSX Element type Context does not have any constructor or call signatures." This is the code in my App.tsx file import { Context } from './interfaces/c ...

Exploring the World of Angular: Abstracts and Data Transformations

Facing a perplexing issue with a component that is based on an abstract class, or at least that's my assumption. There are multiple sibling components rendered using *ngFor based on an array length. These siblings, derived from an abstract class, rec ...

The interface is unable to populate the Array of Elements

When using Angular, I send a request and save the response in a variable: conversations: Conversation[]; // ChatService getConversations() { return this.http.get<Conversation[]>('/chat/conversations'); } this.chatService.getConversat ...

Despite the presence of a producer and topic, sending Kafka messages is proving to be a challenge

Currently, I am using TypeScript and the KafkaJS library on my local machine with a single Kafka broker. After successfully connecting a producer, confirming the creation of my topic, and creating messages like so: const changeMessage = { key: id, ...

How to seamlessly incorporate Polymer Web Components into a Typescript-based React application?

Struggling to implement a Polymer Web Components tooltip feature into a React App coded in TypeScript. Encountering an error during compilation: Error: Property 'paper-tooltip' does not exist on type 'JSX.IntrinsicElements' To resolve ...

Employ the VSTS node API to retrieve all commits within a specified branch

I have been utilizing the vsts-node-api with reasonable success. However, my goal is to retrieve all commits in a specific branch, as detailed in the REST API documentation located here. Unfortunately, the node api only allows for commit queries in a rep ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

How can I assign two different colors based on the type in Typescript?

I am configuring a color property based on the nature of the display. colorStyle: { textAlign: "center", backgroundColor: "transparent", color: (theme.colors.BaseColor.Red as any).Red4, } The cu ...

typescriptIn React Router v5 with TypeScript, an optional URL parameter is implemented that can have an undefined

I'm currently working with react-router v5.1 and TypeScript, and I have set up the following route configurations: <Router basename="/" hashType="slash"> <Switch> <Route path="/token/:tokenName"> <TokenPag ...