TypeScript Compiler Diagnostics
TS2540: Assignment to readonly property
A readonly property prevents direct writes through that typed reference after initialization. When an update is intended, construct a replacement object with the new value. Readonly is a static restriction, not deep runtime freezing; other aliases may still mutate the original object. Baseline: TypeScript 5.8.3 with the shown configuration. Reproduce in one directory and create the corrected project in another. The diagnostic can have other causes; inspect its location and message before choosing a correction. Both projects keep strict checking enabled.
Formal Syntax & Structure
typescript syntaxtypescript
TS2540 (compiler diagnostic code, not TypeScript syntax)Working Example
Example Snippettypescript
// INTENTIONALLY INVALID — reproduce// File: tsconfig.json (omit this label){ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "types": [], "lib": [ "ES2022", "DOM" ], "noEmitOnError": true, "outDir": "dist" }, "files": [ "main.ts" ]}
// File: main.ts (omit this label)type State = { readonly count: number };const state: State = { count: 1 };state.count = 2;
// Run: tsc -p . --pretty false// Expected: TS2540; no output emitted.
// CORRECTED PROJECT — separate directory// File: tsconfig.json (omit this label){ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "types": [], "lib": [ "ES2022", "DOM" ], "noEmitOnError": true, "outDir": "dist" }, "files": [ "main.ts" ]}
// File: main.ts (omit this label)type State = { readonly count: number };const state: State = { count: 1 };const next: State = { ...state, count: 2 };console.log(state.count, next.count);
// Run: tsc -p . --pretty false// Expected: no diagnostics.// Run: node dist/main.js// Expected stdout: 1 2