Skip to content

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 readonly

  • Mutating an object typed as Readonly<T>

  • Calling mutating methods on a readonly array

  • Assigning to a property of a const object (shallow readonly)

Minimal example

✗ Broken code
interface Point { readonly x: number; y: number; }
const p: Point = { x: 10, y: 20 };
p.x = 30; // Error: x is readonly
✓ Fixed code
interface Point { readonly x: number; y: number; }
const p: Point = { x: 10, y: 20 };
const updated: Point = { ...p, y: 30 }; // create new object

Create a new object with the updated value instead of mutating the readonly property.

How to diagnose

  • Check if the property or type has a readonly modifier

  • Check if the object is typed as Readonly<T> or readonly 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 readonly modifier if mutation is intended

  • Use 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

Related Resources

Related Glossary

← Back to language