TS2540
TypeScriptERRORNotableType SystemHIGH confidence

Cannot assign to property because it is a read-only property

What this means

An attempt was made to assign a new value to a property that is marked as 'readonly'.

Why it happens
  1. 1Trying to change the value of a property marked with the 'readonly' modifier.
  2. 2Assigning a value to a 'readonly' property inside a method other than the constructor.
  3. 3Mutating a 'readonly' array, for example by using 'push()' or 'splice()'.
How to reproduce

Assigning a value to a readonly property after initialization.

trigger — this will error
trigger — this will error
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.

Remove the 'readonly' modifier
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.

Create a new object
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.

What not to do

Cast the object to a mutable type

This circumvents the type system and violates the intended immutability contract of the type.

Sources
Official documentation ↗

microsoft/TypeScript src/compiler/diagnosticMessages.json

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All TypeScript errors