TypeScript ยท Chapter 18 of 44

Optional and Readonly Properties

Interfaces and type aliases can mark properties as optional by adding a question mark after the property name. Optional properties do not need to be present on every object of that type.

Properties can also be marked as `readonly`, meaning they can be set once (usually when the object is created) but cannot be reassigned afterward. This helps prevent accidental mutation of important data.

Syntax
interface User {
  readonly id: number;
  name: string;
  age?: number;
}

Optional properties

Adding `?` after a property name, like `age?: number;`, means that property may be omitted entirely. TypeScript treats a missing optional property as `undefined`.

Readonly properties

Adding the `readonly` modifier before a property, like `readonly id: number;`, prevents any code from reassigning that property after the object is created.

Example 1 (typescript)
interface User {
  name: string;
  age?: number;
}

const u1: User = { name: "Ana" };
const u2: User = { name: "Bo", age: 40 };
console.log(u1.age, u2.age);
Output
undefined 40

age is optional, so u1 can omit it entirely and it becomes undefined.

Example 2 (typescript)
interface Point {
  readonly x: number;
  readonly y: number;
}

const p: Point = { x: 1, y: 2 };
// p.x = 5; // Error: cannot assign to readonly property
console.log(p.x, p.y);
Output
1 2

readonly properties can be set at creation but cannot be changed afterward.

Key points

  • A question mark `?` after a property name makes it optional.
  • Missing optional properties are treated as undefined.
  • The `readonly` modifier prevents reassigning a property after creation.
  • Optional and readonly can both be used on the same property.
๐Ÿ’ก Note: readonly only prevents reassignment of the property itself; it does not deeply freeze nested objects.

๐Ÿ“ Quick Quiz

1. How do you mark a property as optional?

2. What does the readonly modifier prevent?

3. What is the value of a missing optional property?