0Pricing
TypeScript Academy · Lesson

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);

All lessons in this course

  1. Optional Chaining with ?.
  2. Nullish Coalescing with ??
  3. Combining ?. and ??
  4. Optional Calls and Element Access
← Back to TypeScript Academy