Combining ?. and ??
Pair optional chaining with sensible default values.
A Perfect Pairing
Optional chaining and nullish coalescing are designed to work together. The pattern obj?.value ?? fallback safely reads a nested value and supplies a default if it's missing. It's one of the most useful idioms in modern TypeScript.
type User = { profile?: { name?: string } };
const u: User = {};
const name = u.profile?.name ?? 'Anonymous';
console.log(name);How the Pattern Works
First ?. evaluates the chain, yielding the value or undefined. Then ?? checks that result: if it's nullish, the fallback is used. Two operators, one clean expression.
type Cfg = { server?: { port?: number } };
const cfg: Cfg = { server: {} };
const port = cfg.server?.port ?? 8080;
console.log(port);