实现说明
顶层就这几处状态:host、port、max、ttlMs。
顶层对象字面量把 count 定成普通值——没有派生,背后也没有导入。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 状态都挂在模块顶层:host、port、max。
核心语句
const called = config.hooks?.onReady?.('primary') ?? 'no hook';
const host = config.db?.host ?? '127.0.0.1';
const ttlMs = config.cache?.ttlMs ?? 60_000;
代码示例
// 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);