Optional and readonly properties
Concept and syntax
note?: string permits omission; reading note can produce undefined. readonly id: number restricts assignment through the typed reference after initialization. These modifiers are independent: a property can be optional, readonly, both or neither. Use an explicit undefined check for an optional string and build a replacement object when a readonly field must change. Readonly does not freeze the object.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
const item: { readonly id: number; note?: string } = { id: 3 };console.log(item.id, item.note === undefined);item.note = "ok";console.log(item.note);Expected output (one line per log):
3 trueokCommon mistake
Intentionally invalid; check this snippet separately. Do not run it.
const item: { readonly id: number; note?: string } = { id: 3 };item.id = 4;Expected compiler diagnostic: TS2540. Readonly rejects this write; optional applies only to note. A new record can have a new id.
Practice and recap
Create a record with readonly id and optional note. Assign a note, then attempt to reassign id; explain each outcome.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Optional and readonly properties — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which modifier permits omitting a property?
Does readonly imply optional?
Which update is permitted through item?
const item: { readonly id: number; note?: string } = { id: 3 };item.id = 4;