Cannot assign to 'X' because it is a read-only property
Error message
Cannot assign to read-only property
Quick summary
You tried to assign a new value to a property marked as readonly, or to a Readonly<T> object. TypeScript prevents mutations of readonly properties at compile time.
Why this happens
Assigning to a property declared with
readonlyMutating an object typed as
Readonly<T>Calling mutating methods on a
readonlyarrayAssigning to a property of a
constobject (shallow readonly)
Minimal example
interface Point { readonly x: number; y: number; }
const p: Point = { x: 10, y: 20 };
p.x = 30; // Error: x is readonlyinterface Point { readonly x: number; y: number; }
const p: Point = { x: 10, y: 20 };
const updated: Point = { ...p, y: 30 }; // create new objectCreate a new object with the updated value instead of mutating the readonly property.
How to diagnose
Check if the property or type has a
readonlymodifierCheck if the object is typed as
Readonly<T>orreadonly T[]Determine if the mutation is necessary or if a new object should be created
How to fix
Create a new object with the updated value (immutable update)
Remove the
readonlymodifier if mutation is intendedUse a non-readonly copy:
{ ...obj, prop: newValue }Cast to a mutable type if you're certain mutation is safe
How to prevent
Use immutable update patterns with spread syntax
Be intentional about which properties are readonly
Use Readonly<T> consistently for immutable data flows