Skip to content

类型 Narrowing in TypeScript

如何 TypeScript refines union 类型内部 conditional 分支 using 类型 guards.

你将学到

  • 什么类型 narrowing 是 and 为什么它 是必要 for unions
  • Narrowing 使用 typeof, instanceof, and in 运算符
  • Discriminated unions for reliable narrowing
  • 如何 control flow analysis tracks narrowed 类型

概念讲解

The Need for Narrowing

When a variable has a union type like 字符串 | 数字, you cannot call string-specific methods on it — the compiler does not know which type is in play. Narrowing is the process of refining the type within a conditional branch so the compiler knows the exact type. After a narrowing check, TypeScript gives you the narrowed type inside that branch, letting you access type-specific properties safely.

Narrowing Techniques

The three main narrowing tools are: typeof for primitives (typeof x === "字符串"), instanceof for classes (x instanceof Date), and the in operator for object property presence ("name" in obj). Each tells the compiler which branch of a union applies. TypeScript also narrows on truthiness checks, equality comparisons (x === 空), and custom type guard functions (covered in the next lesson).

Discriminated Unions

A discriminated union is a union where every member has a common property with a unique literal value — the discriminant. For example, 类型 事件 = { 类型: "点击"; x: 数字 } | { 类型: "scroll"; y: 数字 }. The 类型 property discriminates the union. In a switch on 事件.类型, TypeScript narrows to the exact member in each case. This pattern is the most reliable narrowing strategy for complex unions.

示例代码

              // typeof narrowing for primitives.
function pad(value: string | number): string {
  if (typeof value === "number") {
    // Here, value is narrowed to number.
    return value.toFixed(2);
  }
  // Here, value is narrowed to string.
  return value.padStart(10, " ");
}

// Discriminated union — 'type' is the discriminant.
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      // Narrowed to the circle variant.
      return Math.PI * shape.radius ** 2;
    case "square":
      // Narrowed to the square variant.
      return shape.size ** 2;
  }
}

console.log(pad(42), pad("hi"));
console.log(area({ kind: "circle", radius: 5 }));
console.log(area({ kind: "square", size: 4 }));
            

Narrowing refines union 类型内部分支. typeof handles primitives, instanceof handles 类, in 检查属性 presence. Discriminated unions 使用常见 literal 字段是 大多数 robust 模式.

动手试一试

  • JSON 到 TypeScript

    Polymorphic API 响应经常 produce discriminated unions.

  • Code Diff

    Compare narrowed and 非-narrowed code 到 see safety difference.

常见错误

错误写法

Accessing union-特定属性不使用 narrowing 首先

正确做法

编译器仅 允许类型-特定 access 之后 narrowing 检查. Use typeof, instanceof, in, or discriminant 切换到 narrow 之前 accessing.

错误写法

Forgetting 那个 narrowing 做不 persist 之外分支

正确做法

Narrowing applies 仅在内 conditional 块. 之后如果/else, 类型 reverts 到完整 union. Re-narrow or extract narrowed logic 到 helper.

练习 类型 Narrowing in TypeScript

11 个练习

练习 类型 Narrowing in TypeScript

查阅不认识的术语

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

查看术语表

动手做项目

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

查看项目

解读错误信息

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

查看错误