Lingua-e
JavaScript

What is a TS2540: Readonly Violation?

← Errors

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.

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.

How to fix it

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.

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" };

Related errors

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