What is optional chaining in TypeScript?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid TypeScript basics — a prerequisite for any developer role.

Answer

Optional chaining (?.) is a JavaScript/TypeScript operator that safely accesses nested properties or calls methods without throwing an error if an intermediate value is null or undefined. Instead of an error, it short-circuits and returns undefined. Property access: user?.address?.street — returns undefined if user or address is nullish. Method call: obj?.method?.(args) — only calls the method if obj and method are not nullish. Array access: arr?.[0]. TypeScript understands optional chaining and correctly narrows types after the ?. — it knows the result type includes undefined. Combine with nullish coalescing for defaults: const city = user?.address?.city ?? "Unknown". Without optional chaining, you would write: user && user.address && user.address.street — much more verbose. Optional chaining was introduced in TypeScript 3.7 and compiles down to compatibility checks for older targets.

Pro Tip

This topic has TypeScript-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.