← 中文资源

简体中文版本

可选链与空值合并的默认值

用可选链读取可能缺失的嵌套配置,再用空值合并给默认值:?? 只对 null 和 undefined 兜底,0 与空串是合法值,可选调用在钩子不存在时也不会抛错。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

顶层就这几处状态: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);