Sub topic 6
Optional chaining with ?.
Assume you know basic TypeScript types, interfaces, union types, and JavaScript's null and undefined. This chapter focuses on how optional chaining safely reads values that may be missing.
Optional chaining uses ?. to stop an expression when the value on its left is null or undefined. Instead of throwing an error, the whole expression produces undefined.
interface User {
name: string;
address?: {
city?: string;
};
}
function cityOf(user: User): string {
return user.address?.city ?? "unknown";
}
console.log(cityOf({ name: "Ada" })); // unknown
console.log(cityOf({
name: "Grace",
address: { city: "New York" }
})); // New YorkThe address property is optional. Therefore, user.address has a type that includes undefined. The expression user.address?.city reads city only when address exists.
How optional chaining short-circuits
Optional chaining can appear before property access, element access, or a function call.
type Settings = {
theme?: string;
shortcuts?: string[];
};
function firstShortcut(settings: Settings): string {
return settings.shortcuts?.[0] ?? "none";
}
type Logger = {
write(message: string): void;
};
function notify(logger: Logger | undefined): void {
logger?.write("Saved");
}In settings.shortcuts?.[0], TypeScript checks whether shortcuts is nullish before reading index 0. In logger?.write("Saved"), the method is called only when logger exists.
Optional chaining does not catch every runtime problem. It only checks the value immediately before ?..
type Profile = {
name: string;
};
function display(profile: Profile | undefined): string {
return profile?.name.toUpperCase() ?? "UNKNOWN";
}Here, profile?.name is safe when profile is missing. However, name is required by the type, so this example assumes that name is a valid string. Optional chaining does not protect against incorrect runtime data such as { name: null }.
You can chain several checks:
type Account = {
owner?: {
contact?: {
email?: string;
};
};
};
function emailOf(account: Account): string {
return account.owner?.contact?.email ?? "no email";
}The result is undefined if any checked link is missing. The ?? operator then supplies the fallback.
Optional chaining is not a truthiness check
Optional chaining stops only for null and undefined. It does not replace valid values such as 0, false, or an empty string.
type Cart = {
itemCount?: number;
};
function countLabel(cart: Cart): string {
const count = cart.itemCount ?? 0;
return `Items: ${count}`;
}
console.log(countLabel({ itemCount: 0 })); // Items: 0
console.log(countLabel({})); // Items: 0A common mistake is to use a truthiness check when zero is meaningful:
function oldCountLabel(cart: Cart): string {
return `Items: ${cart.itemCount || 0}`;
}This produces the same result for this fallback, but || also treats false, "", and NaN as missing. Use ?. to safely access a possibly absent value, and use ?? when the fallback should apply only to null or undefined.
> callout note > Optional chaining prevents an error caused by a missing link in a property path. It does not validate the shape of untrusted data. Parse or validate data from APIs before relying on required properties.
Choosing between narrowing and optional chaining
Use optional chaining when a missing value is an expected case and you can continue with a fallback or an undefined result. Use an explicit check when the value is required for the rest of the function or when you need a different response.
function printCity(user: User): void {
if (user.address?.city === undefined) {
console.log("City is unavailable");
return;
}
console.log(user.address.city.toUpperCase());
}The check narrows user.address?.city for the guarded branch. It also makes the missing-value behavior visible to readers.
Exercise
What does user.preferences?.language ?? "en" return when preferences is undefined, and when language is an empty string?
Show answer
It returns "en" when preferences is undefined. It returns the empty string when language is "", because ?? falls back only for null or undefined.