Optional and readonly modifiers
Concept and syntax
Mapped modifiers +readonly and +? add readonly and optionality; -readonly and -? remove them. The changes apply at the mapped level, not recursively. Removing optionality does not generally promise removal of explicitly declared undefined.
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 Draft<T>={-readonly [K in keyof T]-?:T[K]}; type View<T>={readonly [K in keyof T]?:T[K]}; type Source={readonly count?:number};const d:Draft<Source>={count:1}; d.count=2; const v:View<Source>={}; console.log(d.count,Object.keys(v).length);Expected output:
2 0Common mistake
Intentionally invalid; compile separately and do not execute.
type Draft<T>={-readonly [K in keyof T]-?:T[K]}; type View<T>={readonly [K in keyof T]?:T[K]}; type Source={readonly count?:number};const d:Draft<Source>={};Expected diagnostic: TS2741. -? makes count required.
Practice and recap
Remove only readonly and compare assignment of an empty object.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Optional and readonly modifiers — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Optional and readonly modifiers is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Draft<T>={-readonly [K in keyof T]-?:T[K]}; type View<T>={readonly [K in keyof T]?:T[K]}; type Source={readonly count?:number};const d:Draft<Source>={count:1}; d.count=2; const v:View<Source>={}; console.log(d.count,Object.keys(v).length);Which diagnostic and explanation match the rejected example under the lesson settings?
type Draft<T>={-readonly [K in keyof T]-?:T[K]}; type View<T>={readonly [K in keyof T]?:T[K]}; type Source={readonly count?:number};const d:Draft<Source>={};What changes if only -readonly is used in Draft?