Lingua-e
← Errors
JavaScript

TS2540: Readonly Violation: What It Means and How to Fix It

Error reference

TS2540: Readonly Violation

Language

JavaScript

Severity

Medium

When it happens

TypeScript error TS2540 is reported when code attempts to assign to a property marked as readonly.

Potential fixes

Treat readonly values as immutable and create new objects with the updated values using spread or structuredClone. If mutation is necessary, remove readonly from the interface. Use as unknown as MutableType only as a last resort and document why.

Deep dive

TypeScript error TS2540 is reported when code attempts to assign to a property marked as readonly. The readonly modifier makes a property immutable after initialization, providing compile-time protection against accidental mutation.

Why it happens

  • Directly assigning to a property declared with readonly.
  • Mutating a property of a Readonly<T> or ReadonlyArray<T> type.
  • Trying to modify a tuple element beyond its declared length.
  • Attempting to write to a class property decorated with readonly outside the constructor.

Potential fixes

Treat readonly values as immutable and create new objects with the updated values using spread or structuredClone. If mutation is necessary, remove readonly from the interface. Use as unknown as MutableType only as a last resort and document why.

Examples

JavaScript

Code that triggers the error

interface Config {
  readonly apiUrl: string;
}

const config: Config = { apiUrl: "https://api.example.com" };
config.apiUrl = "https://other.com";

Error output

error TS2540: Cannot assign to 'apiUrl' because it is a read-only property.

Fixed code

interface Config {
  readonly apiUrl: string;
}

const config: Config = { apiUrl: "https://api.example.com" };
// Create a new object instead of mutating
const updatedConfig: Config = { ...config, apiUrl: "https://other.com" };

Practice in English

How would you explain a TS2540: Readonly Violation to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free