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.
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.
interface User {
name: string;
age?: number;
}
const u1: User = { name: "Ana" };
const u2: User = { name: "Bo", age: 40 };
console.log(u1.age, u2.age);undefined 40age is optional, so u1 can omit it entirely and it becomes undefined.
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);1 2readonly 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.
