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
}
If you want to prevent any of the object's properties from being modified, you can use the type utility Readonly<Type>
, like this:
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:
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
}