Sub topic 4
Optional and readonly properties
This chapter assumes basic TypeScript annotations, JavaScript objects, and functions. You should also be able to run the TypeScript compiler or read its editor errors.
Optional and readonly properties describe how an object may be used:
- An optional property may be missing.
- A
readonlyproperty may be read but not assigned after initialization through that type.
Both interfaces and type aliases support these modifiers.
Optional properties
Add ? after a property name to make it optional:
interface User {
id: number;
name: string;
email?: string;
}
type Product = {
sku: string;
description?: string;
};
const user: User = { id: 1, name: "Ada" };
const product: Product = { sku: "TS-101" };The object can omit email and description. When you read an optional property, TypeScript includes undefined in its type because the property might not exist.
function emailLabel(user: User): string {
if (user.email === undefined) {
return "No email";
}
return user.email.toLowerCase();
}Checking for undefined is important when strictNullChecks is enabled. This setting is part of the recommended strict compiler configuration.
By default, TypeScript often treats these two assignments similarly:
const first: User = { id: 1, name: "Ada" };
const second: User = { id: 1, name: "Ada", email: undefined };With exactOptionalPropertyTypes: true, an optional property means “the property may be absent.” It does not automatically mean “the property may be present with the value undefined.” If both states are valid, write the type explicitly:
interface SearchOptions {
query?: string | undefined;
}Readonly properties
Place readonly before a property to prevent assignment through that type:
interface Account {
readonly id: number;
name: string;
}
type Coordinates = {
readonly latitude: number;
readonly longitude: number;
};
const account: Account = { id: 10, name: "Grace" };
account.name = "Grace Hopper";
// account.id = 11; // Error: Cannot assign to a readonly propertyreadonly is checked by TypeScript. It does not freeze the JavaScript object at runtime. It also applies only to the property where it appears. A nested object remains mutable unless its own properties are readonly.
interface Settings {
readonly preferences: {
theme: string;
};
}
const settings: Settings = { preferences: { theme: "light" } };
// settings.preferences = { theme: "dark" }; // Error
settings.preferences.theme = "dark"; // AllowedUse Object.freeze when you need runtime protection, remembering that its typing and runtime behavior are separate concerns.
Combining both modifiers
A property can be optional and readonly:
interface Message {
readonly id: number;
readonly sentAt?: Date;
text: string;
}The sentAt property may be absent, and it cannot be assigned after the object is created through a Message reference.
| Declaration | Meaning |
|---|---|
| `name: string` | Required and writable |
| `name?: string` | Optional and writable |
| `readonly name: string` | Required and read-only |
| `readonly name?: string` | Optional and read-only |
A practical mental model
When choosing these modifiers, ask two separate questions: must the caller provide the property, and should the caller be allowed to replace it? Use ? for the first decision and readonly for the second.
Exercise
What is wrong with assigning user.email.toLowerCase() directly when email is declared as email?: string, and how should you fix it?
Show answer
The property may be absent, so its type includes undefined. Check user.email before calling toLowerCase, or use a safe fallback such as user.email?.toLowerCase() ?? "No email".