Skip to content

Nullish Coalescing

一句话解释

nullish coalescing 运算符 (??) 返回正确边 仅如果左 是空 or undefined, unlike || 哪个检查所有 falsy 值.

用大白话说

nullish coalescing 运算符 (??) provides 默认值 for 空 or undefined. x ?? fallback returns x if x is not null/undefined, otherwise returns fallback. It only checks for null and undefined — not 0, empty string, or false.

This differs from the || operator, which checks all falsy values. 0 || 5 returns 5 (because 0 is falsy), but 0 ?? 5 returns 0 (because 0 is not nullish). This is important when 0 or "" are valid values.

Nullish coalescing is available in TypeScript 3.7+ and is standard JavaScript (ES2020). It is commonly used with optional chaining: 配置.timeout ?? 3000.

示例

typescript
const count = 0;
console.log(count || 10);  // 10 (0 is falsy)
console.log(count ?? 10);  // 0 (0 is not nullish)

const name = "";
console.log(name || "Anonymous"); // "Anonymous"
console.log(name ?? "Anonymous"); // ""

?? 仅 falls 后面 for 空/undefined, preserving 有效 falsy 值如 0 and ''.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表