Optional Chaining And Nullish Coalescing Defaults

Read nested config with optional chaining and nullish coalescing, where 0 and empty string stay valid because ?? only falls back on null and undefined.

TypescriptConfig Management

Code

typescriptsnippet
23 lines
// Optional chaining (?.) 与 nullish coalescing (??) 读取嵌套配置
interface Config {
  db?: { host?: string; port?: number; pool?: { max?: number } };
  cache?: { ttlMs?: number };
  hooks?: { onReady?: (name: string) => string };
}

const config: Config = { db: { host: 'localhost', port: 5432 } };

// 任一层缺失或 undefined 都安全落到默认值
const host = config.db?.host ?? '127.0.0.1';
const port = config.db?.port ?? 5432;
const max = config.db?.pool?.max ?? 10;
const ttlMs = config.cache?.ttlMs ?? 60_000;
console.log(`${host}:${port} pool=${max} ttl=${ttlMs}`);

// 与 || 的差异:?? 只对 null / undefined 兜底,0 和 '' 是合法值
const retries = { count: 0 } as const;
console.log(retries.count ?? 3, retries.count || 3);

// 可选调用:onReady 不存在时表达式直接是 undefined,不抛错
const called = config.hooks?.onReady?.('primary') ?? 'no hook';
console.log(called);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

localhost:5432 pool=10 ttl=60000
0 3
no hook

Inside the snippet

Top-level bindings host, port, max, ttlMs hold the demo state — nothing sits inside a function scope.

The top-level object literal pins count as plain values — no derivation, no imports behind them.

Key statements

const called = config.hooks?.onReady?.('primary') ?? 'no hook';
const host = config.db?.host ?? '127.0.0.1';
const ttlMs = config.cache?.ttlMs ?? 60_000;

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `host`, `port`, `max`.