Fixing TS2540 “Cannot assign to … because it is a read-only property” in TypeScript
error TS2540: Cannot assign to 'id' because it is a read-only property. is the error you get when you assign a value to a read-only (readonly) property. It goes away when you create a new object instead of changing the existing one, or, if the value is meant to change, when you remove readonly from the type.
There are several ways to trigger TS2540, including objects created with as const, initial values frozen with Object.freeze, readonly class fields, and properties that have only a getter. I triggered the error in a test environment for each case, applied the fix, and confirmed that the tsc error disappeared.
The test environment was Ubuntu 24.04, Node.js 22.23.5, npm 10.9.9, and TypeScript 7.0.2. I did not test the editor display or versions of TypeScript before 7.
- 1. Triggering TS2540 with a readonly property in an interface
- 2. Fix 1: Create a new object without changing the original
- 3. Fix 2: If the value should change, remove readonly
- 4. A readonly class field can only be assigned in the constructor
- 5. Add a setter to a getter-only property
- 6. For an Object.freeze value, make a copy instead of changing it
- 7. TS2540 also occurs with readonly arrays and enums
- 8. readonly does nothing at runtime
Triggering TS2540 with a readonly property in an interface
I ran npm init -y in an empty folder and installed TypeScript with npm install -D typescript@7.0.2. The tsconfig.json was as follows.
{
"compilerOptions": {
"target": "es2023",
"module": "esnext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true
},
"include": ["src"]
}
In src/interface-ng.ts, I created a Cat type where only id is readonly, and wrote code that assigns to both name and id.
interface Cat {
readonly id: number;
name: string;
}
const tama: Cat = { id: 1, name: "たま" };
tama.name = "タマ";
tama.id = 2;
When I ran npx tsc, one error was reported and the exit code was 1.
$ npx tsc
src/interface-ng.ts(8,6): error TS2540: Cannot assign to 'id' because it is a read-only property.
The message means "id is a read-only property, so it cannot be assigned to." The assignment to name did not produce an error. Only properties marked readonly are blocked. With --pretty, the exact location is shown with a squiggly underline. (In the test, I used sed to remove the control characters that add color, then recorded the output.)
$ npx tsc --pretty
src/interface-ng.ts:8:6 - error TS2540: Cannot assign to 'id' because it is a read-only property.
8 tama.id = 2;
~~
Found 1 error in src/interface-ng.ts:8
Fix 1: Create a new object without changing the original
readonly is a marker that the author of the type has decided this property should not be changed, and tsc reports an error if you assign to it. To change the value while respecting that rule, leave the original object alone and create a new one with the spread syntax.
const tama: Cat = { id: 1, name: "たま" };
tama.name = "タマ";
const copied: Cat = { ...tama, id: 2 };
console.log(tama, copied);
When I replaced tama.id = 2; with this approach, npx tsc printed nothing and exited with code 0.
The same applies when a function argument is typed as Readonly<T>. As described in the Readonly<Type> documentation, Readonly<T> is a type in which every property of T is readonly. I tested this with src/readonly-util-ng.ts below.
type Settings = {
theme: string;
fontSize: number;
};
function render(settings: Readonly<Settings>) {
settings.fontSize = 16;
return settings.theme;
}
render({ theme: "light", fontSize: 14 });
$ npx tsc
src/readonly-util-ng.ts(7,12): error TS2540: Cannot assign to 'fontSize' because it is a read-only property.
When I stopped modifying the argument and instead made a copy inside the function, such as const fixed = { ...settings, fontSize: 16 };, the exit code was 0.
Fix 2: If the value should change, remove readonly
If you wrote the type yourself and marked a property readonly even though you intend to change it, the straightforward fix is to remove readonly from the type.
An object with as const also has all its properties treated as readonly (see the const assertions section of the TypeScript 3.4 release notes). I tested this in src/as-const-ng.ts.
const config = {
apiUrl: "https://example.com/api",
retry: 3,
} as const;
config.retry = 5;
$ npx tsc
src/as-const-ng.ts(6,8): error TS2540: Cannot assign to 'retry' because it is a read-only property.
When I removed as const, config.retry = 5; passed without error and the exit code was 0. However, with as const, the type of retry is the literal type 3. Without it, the type widens to number, so assigning 5 becomes allowed. Before removing it, check whether there is a reason to restrict the value type to 3.
If you cannot change the type itself but want to modify the object while building it, you can create a type with readonly removed using -readonly, as described in the mapped types documentation.
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
const draft: Mutable<Cat> = { id: 1, name: "たま" };
draft.id = 2;
console.log(draft);
This draft.id = 2; did not produce an error, and the exit code was 0.
A readonly class field can only be assigned in the constructor
As described in the classes documentation, assignments to a class's readonly fields are blocked outside the constructor. If you try to set the value again inside a method, as in src/class-ng.ts, you get TS2540.
class Counter {
readonly start: number;
count = 0;
constructor(start: number) {
this.start = start;
}
reset(start: number) {
this.start = start;
this.count = 0;
}
}
new Counter(1).reset(5);
$ npx tsc
src/class-ng.ts(10,10): error TS2540: Cannot assign to 'start' because it is a read-only property.
The error occurs only in reset on line 10. The assignment in the constructor on line 6 is allowed. If you want to change start, use a method that returns a new instance.
withStart(start: number) {
return new Counter(start);
}
When I replaced reset with this withStart, the exit code was 0. If the value is naturally meant to be changed inside a method, remove readonly.
Add a setter to a getter-only property
TS2540 can also occur even when you did not write readonly. A property that has a get but no set is automatically treated as readonly (see the getters and setters section of the classes documentation). I tested this in src/getter-ng.ts.
class Circle {
constructor(private r: number) {}
get radius() {
return this.r;
}
}
const circle = new Circle(1);
circle.radius = 2;
$ npx tsc
src/getter-ng.ts(10,8): error TS2540: Cannot assign to 'radius' because it is a read-only property.
If you want to allow assignment from outside, add a set with the same name.
set radius(value: number) {
this.r = value;
}
With this, circle.radius = 2; passed, and the exit code was 0.
For an Object.freeze value, make a copy instead of changing it
The return value of Object.freeze has the type Readonly<T>, so assigning to it also produces TS2540 (src/freeze-ng.ts).
const defaults = Object.freeze({ lang: "ja", pageSize: 20 });
defaults.pageSize = 50;
$ npx tsc
src/freeze-ng.ts(3,10): error TS2540: Cannot assign to 'pageSize' because it is a read-only property.
This error is not only about types. I prepared src/freeze-runtime.ts, which silences the type check with // @ts-expect-error. It prints the exception if the assignment throws.
const defaults = Object.freeze({ lang: "ja", pageSize: 20 });
try {
// @ts-expect-error pageSize is read-only
defaults.pageSize = 50;
} catch (e) {
console.log(String(e));
}
console.log(defaults.pageSize);
Because tsconfig.json has noEmit: true, I overrode it with --noEmit false to output JavaScript to out/, then ran it with Node.js 22. (In the test, I appended && cat out/freeze-runtime.js to the command so that the output JavaScript is also shown.) The assignment threw a TypeError, and the value remained 20.
$ rm -rf out; npx tsc --noEmit false --rootDir src --outDir out
$ node out/freeze-runtime.js
TypeError: Cannot assign to read only property 'pageSize' of object '#<Object>'
20
The output JavaScript began with "use strict";. As described in the MDN documentation for Object.freeze, assignment to a frozen object fails, and in strict mode it throws a TypeError.
If you want to change a value created with Object.freeze, do not modify the type. Instead, create a new object, such as { ...defaults, pageSize: 50 }.
TS2540 also occurs with readonly arrays and enums
With a readonly number[] array, assigning to length produced TS2540. Assigning to an element produces TS2542, which has a different number.
const scores: readonly number[] = [72, 95, 88];
scores[0] = 100;
scores.length = 0;
$ npx tsc
src/array-ng.ts(3,1): error TS2542: Index signature in type 'readonly number[]' only permits reading.
src/array-ng.ts(4,8): error TS2540: Cannot assign to 'length' because it is a read-only property.
Assigning to an enum member also produced TS2540.
enum Color {
Red,
Blue,
}
Color.Red = 5;
$ npx tsc
src/enum-ng.ts(6,7): error TS2540: Cannot assign to 'Red' because it is a read-only property.
Enum members are not meant to be changed, so review the code that performs the assignment.
readonly does nothing at runtime
Unlike Object.freeze, readonly is a rule that applies only during type checking. The object types documentation also states that runtime behavior does not change. I kept only the assignment to id from the original Cat example, added // @ts-expect-error, and output the JavaScript with the same command as before. The readonly modifier was removed, and the assignment ran as written.
$ rm -rf out; npx tsc --noEmit false --rootDir src --outDir out && cat out/runtime.js
"use strict";
const tama = { id: 1, name: "たま" };
// @ts-expect-error id is readonly
tama.id = 2;
console.log(tama.id);
$ node out/runtime.js
2
Also, assigning a value of a type with readonly properties to a variable whose type does not have readonly did not produce an error.
const tama: Cat = { id: 1, name: "たま" };
const writable: { id: number; name: string } = tama;
writable.id = 2;
console.log(tama.id);
npx tsc exited with code 0, and running the code printed 2. The object types documentation also explains that readonly is not considered when checking whether one type can be assigned to another, so a value can be changed through a different name (an alias). TS2540 stops direct assignments through the same variable, but it does not prevent changes made through such aliases.





