What it is and why to use it
Optional chaining stops a property access or call when its left-hand value is null or undefined. Nullish coalescing supplies a fallback only for those two values. Together they are useful for optional nested data while preserving legitimate values such as zero or an empty string.
Common mistakes and limitations
Optional chaining protects only the nullish part of the chain where it is used. It does not validate unknown data or catch exceptions thrown by a getter or function. Do not use it to hide a field that your program actually requires.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
const city = user.address?.city ?? "Unknown";Examples
Optional Chaining and Nullish Defaults
Standalone TypeScript 5.8+ example; expected output is explained below.
type Settings = { audio?: { volume: number } };
function volume(settings: Settings): number {
return settings.audio?.volume ?? 50;
}
console.log(volume({}));
console.log(volume({ audio: { volume: 0 } }));- When audio is missing, ?. produces undefined instead of attempting to read its volume.
- The ?? operator substitutes 50 for that undefined result.
- A volume of zero is kept. Using || here would wrongly replace zero with the default.
- Expected output: 50 0
Best practices
- Optional chaining protects only the nullish part of the chain where it is used. It does not validate unknown data or catch exceptions thrown by a getter or function. Do not use it to hide a field that your program actually requires.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook