Objects & Interfaces
Optional & Readonly Properties
Master optional properties (?), readonly modifier, nested immutability, Readonly utility type, and preventing runtime mutations in TypeScript.
Object types and interfaces in TypeScript support property modifiers to mark properties as Optional (?) or Readonly (readonly).
1. Optional Properties (?)
Marking a property with a ? means the property is not required when creating an object. The property's type expands to Type | undefined.
2. Safe Access with Nullish Coalescing and Optional Chaining
When working with optional properties, use Optional Chaining (?.) and Nullish Coalescing (??) to handle undefined safely:
3. Readonly Properties (readonly)
The readonly modifier prevents reassignment of a property after object initialization.
4. readonly vs const
const: Applies to variable bindings (prevents reassigning the variable reference).readonly: Applies to object properties inside interfaces/types (prevents mutating property values).5. Shallow vs Deep Readonly
The readonly property modifier is shallow. Mutating nested object properties inside a readonly property is allowed unless those nested properties are also marked readonly.
6. Interactive Code Playground
Test readonly and optional property modifiers below:
7. Common Pitfalls & Edge Cases
readonly: readonly is enforced solely by TypeScript's compiler (tsc). At JavaScript runtime, readonly properties can still be mutated if accessed via untyped code or JavaScript libraries.8. Summary Comparison Table
| Modifier | Syntax | Effect | |
|---|---|---|---|
| Optional | prop?: T | Property can be omitted (T \ | undefined) |
| Readonly | readonly prop: T | Prevents property assignment after initialization |
readonly prop?: T | Optional property that cannot be mutated once set |