Skip to content

Readonly violation: mutating a readonly property

Quick summary

You tried to push to a readonly array or assign to a readonly property — TypeScript blocks mutations of readonly types.

Why this happens

  • A ReadonlyArray is passed to a function that tries to mutate it with push, pop, or splice

  • A readonly property is assigned a new value, which TypeScript does not allow

  • A Readonly<T> type is used but the code tries to modify it as if it were mutable

Minimal example

✗ Broken code
function addItem(list: ReadonlyArray<number>, item: number) {
  list.push(item); // error: Property 'push' does not exist on type 'readonly number[]'
}
✓ Fixed code
function addItem(list: ReadonlyArray<number>, item: number): number[] {
  return [...list, item]; // non-mutating, returns new array
}

Using the spread operator creates a new array with the added item, avoiding mutation of the readonly input array.

How to diagnose

  • Read the TS error: 'Cannot assign to readonly property' or 'Index signature is readonly'

  • Check if the type is Readonly<T> or ReadonlyArray<T> and the code tries to mutate it

  • Look for a type assertion that may have stripped the readonly modifier

How to fix

  • Create a mutable copy before modifying: const mutable = [...readonlyArray]; mutable.push(item)

  • Change the type to mutable (T[] instead of ReadonlyArray<T>) if mutation is intended

  • Use a non-mutating update pattern: const updated = [...arr, item] instead of arr.push(item)

How to prevent

  • Use readonly types for data that should not be mutated, and create copies before modification

  • Prefer non-mutating update patterns (spread, map, filter) over in-place mutation

Related Resources

Related Glossary

Related Lessons

← Back to language