Cannot assign to property because it is a read-only property
An attempt was made to assign a new value to a property that is marked as 'readonly'.
- 1Trying to change the value of a property marked with the 'readonly' modifier.
- 2Assigning a value to a 'readonly' property inside a method other than the constructor.
- 3Mutating a 'readonly' array, for example by using 'push()' or 'splice()'.
Assigning a value to a readonly property after initialization.
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 10, y: 20 };
p.x = 5;expected output
error TS2540: Cannot assign to 'x' because it is a read-only property.
Fix 1
Remove the 'readonly' modifier
WHEN The property is intended to be mutable.
interface Point {
x: number;
y: number;
}
const p: Point = { x: 10, y: 20 };
p.x = 5;Why this works
Removing the modifier allows the property to be reassigned.
Fix 2
Create a new object
WHEN Immutability is desired.
interface Point {
readonly x: number;
readonly y: number;
}
const p1: Point = { x: 10, y: 20 };
const p2: Point = { ...p1, x: 5 };Why this works
Creating a new object with the updated value preserves the immutability of the original object.
✕ Cast the object to a mutable type
This circumvents the type system and violates the intended immutability contract of the type.
microsoft/TypeScript src/compiler/diagnosticMessages.json
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev