Readonly compatibility
Concept and syntax
Readonly restricts writes through the typed reference; it does not freeze the runtime object or recursively mark nested fields readonly. A mutable alias can change a readonly view. Readonly arrays additionally omit mutating methods and are not assignable to mutable arrays without copying.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
const original={count:1,nested:{value:2}};const view:{readonly count:number;nested:{value:number}}=original;original.count=3;view.nested.value=4;console.log(view.count,view.nested.value);Expected output:
3 4Common mistake
Intentionally invalid; compile separately and do not execute.
const view:{readonly count:number}={count:1};view.count=3;Expected diagnostic: TS2540. Readonly prohibits that assignment through view. Change the design or create a new object.
Practice and recap
Create a readonly nested type and compare which assignments are rejected.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Readonly compatibility — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
const original={count:1,nested:{value:2}};const view:{readonly count:number;nested:{value:number}}=original;original.count=3;view.nested.value=4;console.log(view.count,view.nested.value);Which diagnostic and explanation match the rejected example under the lesson settings?
const view:{readonly count:number}={count:1};view.count=3;