ReviseAlgo Logo

Objects & Interfaces

Optional & Readonly Properties

Master optional properties (?), readonly modifier, nested immutability, Readonly utility type, and preventing runtime mutations in TypeScript.

Last Updated: July 29, 2026 10 min read

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

  • Compiler Erasure of 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

    ModifierSyntaxEffect
    Optionalprop?: TProperty can be omitted (T \undefined)
    Readonlyreadonly prop: TPrevents property assignment after initialization
    | Combined | readonly prop?: T | Optional property that cannot be mutated once set |