Home > Back-end >  How to define readonly object parameter for function in Typescript
How to define readonly object parameter for function in Typescript

Time:12-12

Is there any way to enforce an object parameter cannot be changed in typescript, e.g.

interface MyType {
   prop1: number
}    
function myMethod(param: readonly MyType) {
   // I want TS complain here:
   param.prop1 = 2
}

CodePudding user response:

If you want to prevent any of the object's properties from being modified, you can use the type utility Readonly<Type>, like this:

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) */
}

But if you only want to prevent specific properties from being modified, you can mark 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
}
  • Related