Deep readonly and partial
Concept and syntax
Recursive mapped types can apply readonly or optional modifiers throughout selected nested plain records. This version intentionally targets acyclic data records with primitive leaves; functions, class instances, maps, sets and arrays need separate policy. Deep readonly is not deep runtime freezing.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type DeepRO<T>=T extends object?{readonly [K in keyof T]:DeepRO<T[K]>}:T; type DeepPatch<T>=T extends object?{[K in keyof T]?:DeepPatch<T[K]>}:T; type Model={meta:{count:number;label:string}};const v:DeepRO<Model>={meta:{count:2,label:"tea"}}; const p:DeepPatch<Model>={meta:{count:3}}; console.log(v.meta.label,p.meta?.count);Expected output:
tea 3Common mistake
Intentionally invalid; compile separately and do not execute.
type DeepRO<T>=T extends object?{readonly [K in keyof T]:DeepRO<T[K]>}:T; type DeepPatch<T>=T extends object?{[K in keyof T]?:DeepPatch<T[K]>}:T; type Model={meta:{count:number;label:string}};const v:DeepRO<Model>={meta:{count:2,label:"tea"}}; v.meta.count=4;Expected diagnostic: TS2540. The nested count property is readonly through v.
Practice and recap
Add a nested record and compare ordinary Partial with DeepPatch.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Deep readonly and partial — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Deep readonly and partial is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type DeepRO<T>=T extends object?{readonly [K in keyof T]:DeepRO<T[K]>}:T; type DeepPatch<T>=T extends object?{[K in keyof T]?:DeepPatch<T[K]>}:T; type Model={meta:{count:number;label:string}};const v:DeepRO<Model>={meta:{count:2,label:"tea"}}; const p:DeepPatch<Model>={meta:{count:3}}; console.log(v.meta.label,p.meta?.count);Which diagnostic and explanation match the rejected example under the lesson settings?
type DeepRO<T>=T extends object?{readonly [K in keyof T]:DeepRO<T[K]>}:T; type DeepPatch<T>=T extends object?{[K in keyof T]?:DeepPatch<T[K]>}:T; type Model={meta:{count:number;label:string}};const v:DeepRO<Model>={meta:{count:2,label:"tea"}}; v.meta.count=4;Why is a deep readonly annotation not enough to freeze data?