Sub topic 6
Optional chaining with ?.
This chapter assumes you know how null and undefined differ, that strictNullChecks is on, and how to write nullable union types. It also assumes you can narrow a value with if. Earlier chapters covered all of these.
The problem it solves
With strictNullChecks on, a value typed T | undefined can't be dereferenced until you prove it is present. For nested data, the explicit checks pile up:
interface User {
name: string;
address?: { city?: string };
}
function cityVerbose(user: User): string | undefined {
if (user.address !== undefined) {
return user.address.city;
}
return undefined;
}The optional chaining operator ?. collapses this into one expression. If the value on its left is null or undefined, the expression stops and produces undefined. Otherwise it continues as a normal access.
function cityOf(user: User): string {
return user.address?.city ?? "unknown";
}Here user.address?.city has type string | undefined. The ?? operator, covered in the next chapter, replaces undefined with a default.
The three forms
Optional chaining works on property access, element access, and calls.
| Form | Meaning | Example |
|---|---|---|
| `a?.b` | Read property `b` if `a` is not nullish | `user.address?.city` |
| `a?.[expr]` | Index into `a` if `a` is not nullish | `list?.[0]` |
| `a?.(args)` | Call `a` if `a` is not nullish | `callback?.(42)` |
"Nullish" means null or undefined. All three forms can appear in one chain:
interface Settings {
theme?: { colors?: string[] };
onSave?: (id: number) => void;
}
function demo(settings: Settings | null): string | undefined {
settings?.onSave?.(42);
return settings?.theme?.colors?.[0];
}In settings?.onSave?.(42), the first ?. guards settings, which may be null. The second ?. guards onSave, which is an optional member. The call happens only if both are present.
What the compiler infers
When ?. appears in a chain, the type of the whole chain gains undefined. This is true even when the original value was null. The result is always undefined, never null.
function lengthOf(s: string | null): number | undefined {
return s?.length;
}
console.log(lengthOf("abc")); // 3
console.log(lengthOf(null)); // undefined, not nullIf strictNullChecks is off, s could never be typed as nullable in a way the compiler tracks, so ?. adds nothing to the type. The runtime behavior still applies. This is one reason to keep the flag on.
Short-circuiting covers the rest of the chain
When the left side is nullish, evaluation of the entire remaining chain is skipped. That includes later property accesses, later calls, and the arguments inside them.
interface Account {
owner: { name: string };
}
function ownerName(account: Account | undefined): string | undefined {
return account?.owner.name;
}owner is not optional, so the second dot is a plain .. You don't need account?.owner?.name. The chain stops at account if it is missing, and .name is never evaluated. Writing ?. after a member that can't be nullish is allowed. It adds noise and suggests the type allows a case it doesn't.
Arguments are skipped too:
let calls = 0;
function next(): number {
calls++;
return calls;
}
function readItem(box: { items?: number[] }): number | undefined {
return box.items?.[next()];
}
readItem({});
console.log(calls); // 0, because next() was never called
readItem({ items: [10, 20, 30] });
console.log(calls); // 1Only null and undefined short-circuit
Optional chaining tests for nullish values only. Other falsy values such as 0, "", false, and NaN continue through the chain as normal.
function safeLength(s: string | null): number | undefined {
return s?.length;
}
console.log(safeLength("")); // 0, the empty string is not nullish
console.log(safeLength(null)); // undefinedA result of undefined does not always mean the chain stopped early. In list?.[5], the chain may reach the index and find nothing there. Both cases give undefined, so the result can't tell you which happened.
Optional chaining and narrowing
TypeScript understands optional chains in conditions. If a chain is compared to a non-nullish value, every link on the left is narrowed to present.
function cityLength(user: User): number {
if (user.address?.city !== undefined) {
// user.address is known to be defined here, and city is a string
return user.address.city.length;
}
return 0;
}A truthiness check works as well, with the usual caveat about falsy values:
function hasCity(user: User): boolean {
if (user.address?.city) {
return user.address.city.length > 0;
}
return false;
}An empty string city fails the truthiness check, so hasCity returns false for it. For strings and numbers where "" or 0 is legitimate, compare with !== undefined instead.
Optional method calls
The form obj.method?.() calls the method only if it exists. This suits optional methods in interfaces, callbacks, and feature-detected APIs.
interface Logger {
debug?(message: string): void;
info(message: string): void;
}
function start(logger: Logger): void {
logger.debug?.("starting");
logger.info("started");
}
start({ info: (m) => console.log(m) });The this value is preserved. In logger.debug?.("starting"), the method still runs with logger as this.
?.() guards against null or undefined only. If debug holds something that isn't a function, such as a string from untyped data, the call throws a TypeError. The operator doesn't check for callability.
Where optional chaining is not allowed
A few positions are syntax errors, because their meaning would be unclear.
- Assignment targets:
user.address?.city = "Oslo"is rejected. To assign, narrow first with anif. newexpressions:new factory?.()is rejected.- Tagged templates: `
tag?.text` is rejected.
The delete operator does accept a chain: delete user.address?.city removes city when address exists and does nothing otherwise.
Parentheses end the chain
Short-circuiting applies to the chain as one unit. Wrapping part of it in parentheses closes the unit, and what follows runs normally.
function brokenOwner(account: Account | undefined): string {
// return (account?.owner).name;
// Error: '(account?.owner)' is possibly 'undefined'.
return account?.owner.name ?? "none";
}Without parentheses, .name is skipped when account is undefined. With them, .name is evaluated on undefined, which would throw at runtime, and the compiler reports it.
Common mistakes
- Chaining everywhere "to be safe". If a value can't be nullish by its type,
?.is unnecessary. If the value should always be there, a missing value is a bug that?.hides by turning it into a quietundefined. Use?.where absence is a legitimate state in your data. - Expecting
nullback. The result of a short-circuited chain isundefined. Code that checksresult === nullwill never match. - Mixing it up with
||defaults.a?.b || fallbackreplaces any falsyb. Use??when0,"", orfalseare valid values. - Treating the result as the original type. The chain's type includes
undefined. Passing it to a function that wantsstringproduces the same error as any other nullable value, so narrow or provide a default first. - Optional chaining on
any. With values typedany, the compiler can't verify anything, so?.guards against missing values but not against wrong shapes.
Compilation target
Optional chaining became standard JavaScript in ES2020. If your target in tsconfig.json is older, TypeScript rewrites the chain into equivalent explicit checks. You can use ?. regardless of target. Only the emitted JavaScript differs.
Exercise
Given interface Config { server?: { port?: number } }, what do readPort({}) and readPort({ server: { port: 0 } }) return for each of these two implementations? Which one is correct if port 0 is meaningful?
function a(c: Config): number { return c.server?.port || 8080; }
function b(c: Config): number { return c.server?.port ?? 8080; }
Show answer
For {}, both return 8080, because the chain yields undefined. For { server: { port: 0 } }, a returns 8080 because || replaces the falsy 0, while b returns 0 because ?? replaces only null and undefined. If port 0 is meaningful, b is correct.
Exercise
Why does (account?.owner).name fail to compile when account is Account | undefined, while account?.owner.name compiles?
Show answer
The parentheses end the optional chain. account?.owner is typed { name: string } | undefined, and .name is then applied to that value without short-circuiting, so the compiler reports a possibly undefined access. In account?.owner.name, the whole expression is one chain, so .name is skipped when account is undefined.