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.
Code
// 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 hookInside 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.