Skip to content

类型 Narrowing

一句话解释

类型 narrowing 是处理通过哪个 TypeScript refines 值's 类型到 更多特定类型在内 code 块, based on 检查如 typeof, instanceof, or truthiness.

用大白话说

Type narrowing is TypeScript following your code's control flow to figure out a more specific type for a value. When you check a type with if, switch, or other conditionals, TypeScript narrows the type inside that block.

例如, if x is 字符串 | 空, after 如果 (x !== 空), TypeScript narrows x to 字符串 — you don't need to assert it. This is called control flow based type narrowing.

Narrowing works with typeof, instanceof, in, truthiness checks, equality comparisons, and user-defined type guards. TypeScript tracks the narrowed type through if/else, switch, ternary operators, and even assignments.

示例

typescript
function greet(name: string | null) {
  if (name === null) {
    return "Hello, stranger";
  }
  // Here, name is narrowed to string
  return `Hello, ${name.toUpperCase()}`;
}

之后空 检查, TypeScript narrows name 到字符串, 允许 .toUpperCase().

相关术语

解读错误信息

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

查看错误

← 返回术语表