Skip to content

Nullish Coalescing in TypeScript

Provide 默认值 使用 ?? 运算符, 哪个仅 触发 on 空 and undefined.

你将学到

  • 如何 ?? 运算符 differs 从 || 运算符
  • 为什么 ?? 仅 treats 空 and undefined as 空
  • 组合 ?? 使用可选 chaining for safe defaults
  • 常见模式: 配置值, API 响应, and 表单输入

概念讲解

?? vs ||

The nullish coalescing operator (??) returns the right side when the left is 空 or undefined. This differs from the logical OR (||) which returns the right side for any falsy value (including 0, "", and 假). This distinction matters: 数量 || 10 returns 10 when count is 0, but 数量 ?? 10 returns 0 because 0 is not nullish. If 0 is a valid value, you must use ??.

When to Use ??

Use ?? whenever the left value could legitimately be a falsy non-null value. Common cases: numeric counters (0 is valid), empty strings ("" is valid), boolean flags (false is valid), and configuration options where the user explicitly set a falsy value. The || operator is still appropriate when you genuinely want to replace all falsy values, like filtering empty strings from a list.

Combining with Optional Chaining

The ?? operator pairs perfectly with optional chaining (?.). Since ?. returns undefined on short-circuit, ?? provides the fallback: 配置?.timeout ?? 5000 returns the configured timeout if it exists, or 5000 as a default. This one-liner replaces a multi-line conditional check and is the idiomatic way to handle "deeply nested 可选值使用默认" in modern TypeScript.

示例代码

              // ?? only triggers on null and undefined — 0 and "" are preserved.
let count: number | null = 0;
console.log(count ?? 10);  // 0 (not 10, because 0 is not nullish)
console.log(count || 10);  // 10 (|| treats 0 as falsy)

let label: string | undefined = "";
console.log(label ?? "default"); // "" (empty string is preserved)
console.log(label || "default"); // "default" (|| treats "" as falsy)

// Combining ?. with ?? for nested defaults.
interface Config {
  server?: {
    port?: number;
    host?: string;
  };
}

function getPort(config: Config): number {
  return config?.server?.port ?? 3000;
}

function getHost(config: Config): string {
  return config?.server?.host ?? "localhost";
}

console.log(getPort({}));                    // 3000
console.log(getPort({ server: { port: 8080 } })); // 8080
console.log(getHost({ server: { host: "" } }));    // "" (valid empty host)
            

?? 运算符返回正确边 仅 for 空/undefined, preserving 0, 空字符串, and 假. Use 它相反的 || 当 falsy 非-空值 是有效. Pair 使用 ?. for nested defaults.

动手试一试

常见错误

错误写法

Using || 当 0, 假, or 空字符串是 有效值

正确做法

|| replaces 所有 falsy 值. 如果 0, 假, or "" 是 legitimate, use ?? 哪个仅 replaces 空 and undefined. 这个是 常见源 的 subtle bugs.

错误写法

Chaining 多个 ?? 运算符 expecting 首先非-空值

正确做法

?? 是左-associative and 仅检查 one level. For 选择其中多个 candidates, use helper or nested ternary. 每个 ?? 检查仅 它的 immediate 左 operand.

练习 Nullish Coalescing in TypeScript

4 个练习

练习 Nullish Coalescing in TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

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

查看错误