Sub topic 5
Optional and readonly properties
Assume you know basic TypeScript annotations, interfaces, type aliases, JavaScript objects, and functions. This chapter focuses on how optional and readonly members change object compatibility and what you can do through a typed reference.
Optional properties
An optional property is a property that may be absent. Add ? after its name:
interface Profile {
name: string;
bio?: string;
}
const complete: Profile = {
name: "Mina",
bio: "TypeScript developer",
};
const short: Profile = {
name: "Mina",
};A value with a required property can be assigned to a type where that property is optional. The reverse is unsafe because the optional property might be missing.
interface RequiredBio {
bio: string;
}
interface OptionalBio {
bio?: string;
}
const required: RequiredBio = { bio: "Hello" };
const optional: OptionalBio = required; // OK
// @ts-expect-error: bio might be absent
const mustHaveBio: RequiredBio = optional;When you read an optional property with strictNullChecks enabled, TypeScript includes undefined in its type. Your code must handle that possibility.
function printBio(profile: Profile): void {
if (profile.bio !== undefined) {
console.log(profile.bio.toUpperCase());
} else {
console.log("No biography");
}
}You can also use a default value:
function bioLength(profile: Profile): number {
return (profile.bio ?? "").length;
}The nullish coalescing operator, ??, uses the value on the right when the value on the left is null or undefined.
Missing and `undefined` are different
By default, TypeScript often treats these two objects as compatible with an optional property:
interface Settings {
color?: string;
}
const missing: Settings = {};
const explicitlyUndefined: Settings = { color: undefined };Enable exactOptionalPropertyTypes when the difference matters. With that option, color?: string means that color may be absent, but an explicitly present color must be a string. To allow both an absent property and an explicit undefined, write:
interface FlexibleSettings {
color?: string | undefined;
}Readonly properties
A readonly property can be read but cannot be changed through that reference.
interface Account {
readonly id: string;
name: string;
}
const account: Account = {
id: "a-17",
name: "Ravi",
};
account.name = "Ravi Patel";
// @ts-expect-error: id is readonly
account.id = "a-18";readonly is a compile-time restriction. It does not freeze the JavaScript object at runtime. It is also shallow, so nested objects remain changeable unless they have their own readonly members.
interface Preferences {
readonly display: {
theme: string;
};
}
const preferences: Preferences = {
display: { theme: "light" },
};
// The property reference cannot be replaced.
// @ts-expect-error
preferences.display = { theme: "dark" };
// The nested property is still mutable.
preferences.display.theme = "dark";A mutable object can be used where a readonly view is expected. This lets a function inspect a value without being allowed to change it:
interface ReadonlyPoint {
readonly x: number;
readonly y: number;
}
function distanceFromOrigin(point: ReadonlyPoint): number {
return Math.sqrt(point.x ** 2 + point.y ** 2);
}
const point = { x: 3, y: 4 };
console.log(distanceFromOrigin(point)); // 5The caller still owns point and can change it later. The function only receives a readonly view during its call.
Comparing the rules
| Member declaration | Must exist when creating the value? | Can be written through the type? | Read type | Column |
|---|---|---|---|---|
| `name: string` | Yes | Yes | `string` | |
| `name?: string` | No | Yes, if present | `string \ | undefined` |
| `readonly name: string` | Yes | No | `string` | |
| `readonly name?: string` | No | No | `string \ | undefined` |
Common mistakes
- Treating an optional property as an ordinary string without checking for
undefined. - Assuming
readonlyfreezes nested objects. - Assuming
readonlyprotects an object from all other references. - Using
prop?: Twhen the API must distinguish a missing property from a property explicitly set toundefined.
Exercise
Why does const x: { title: string } = { title: undefined }; fail under strict null checks, while const y: { title?: string } = {}; succeeds?
Show answer
The first type requires a present string, and undefined is not a string. The second type permits the property to be absent.