Optional Chaining in TypeScript
Safely access nested properties with the ?. operator without runtime errors.
What you'll learn
- How the ?. operator short-circuits on null and undefined
- Optional method calls and optional element access
- Combining optional chaining with nullish coalescing
- When optional chaining returns undefined vs throwing
Concept
The ?. Operator
Optional chaining (?.) lets you safely access nested properties without manually checking each level for null. Instead of user && user.profile && user.profile.name, you write user?.profile?.name. If any link in the chain is null or undefined, the entire expression short-circuits and returns undefined — no runtime error. This operator was added in TypeScript 3.7 and is now standard in modern JavaScript.
Three Forms of ?.
Optional chaining has three forms: property access (obj?.prop), method call (obj?.method()), and element access (arr?.[index]). The method call form is especially useful for optional callbacks: onComplete?.(result) calls the callback if it exists, otherwise does nothing. All three forms short-circuit to undefined when the left side is null or undefined.
Combining with ??
Optional chaining returns undefined when it short-circuits, which you often want to replace with a default value. The nullish coalescing operator (??) is the perfect partner: user?.name ?? "Anonymous" returns the name if it exists, or "Anonymous" if the chain short-circuits. This combination handles the entire "deeply nested, possibly missing, with a default" pattern in one readable expression.
Example
// Nested data that may be partially missing.
interface User {
profile?: {
name?: string;
address?: {
city?: string;
};
};
}
// Without optional chaining — verbose and error-prone.
function getCityOld(user: User): string | undefined {
if (user.profile && user.profile.address) {
return user.profile.address.city;
}
return undefined;
}
// With optional chaining — clean and safe.
function getCity(user: User): string | undefined {
return user?.profile?.address?.city;
}
// Optional method call — invokes only if defined.
let callback: ((msg: string) => void) | undefined;
callback?.("done"); // no error if callback is undefined
// Combining ?. with ?? for a default value.
function getDisplayName(user: User): string {
return user?.profile?.name ?? "Anonymous";
}
const user: User = { profile: { address: { city: "Paris" } } };
console.log(getCity(user)); // "Paris"
console.log(getDisplayName({})); // "Anonymous"
The ?. operator short-circuits to undefined when any part of the chain is null/undefined. Use it for property access, method calls, and element access. Pair with ?? for defaults.
Try it
- JSON Formatter
Format nested JSON to visualize the chains optional chaining traverses.
- JSON Path
JSONPath queries mirror optional chaining for deep JSON access.
Common mistakes
The mistake
Using optional chaining on a value that is never null
The fix
If the type guarantees the property exists, ?. adds unnecessary overhead and hides type errors. Only use ?. where the type actually includes null or undefined.
The mistake
Confusing optional chaining (?.) with non-null assertion (!.)
The fix
?. returns undefined if the value is null (safe). !. asserts non-null and throws if it is null (unsafe). Use ?. for safety, !. only with proof of non-null.
Practice Optional Chaining in TypeScript
4 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.