typeof(区分原始类型)、 typeof(区分原始类型)、 typeof(区分原始类型)、
TypeScript 词条目录
前端Wiki/TypeScript/进阶/函数与类型守卫

类型守卫与类型缩小

联合类型使用前必须"缩小"到具体成员。内置缩小手段:typeof(区分原始类型)、instanceof(区分类实例)、in(区分结构差异)、相等比较(=== 与字面量)。

自定义类型守卫(type predicate)让编译器学会你的判断逻辑:函数返回类型写成 x is Fish 后,凡是用这个函数做的 if 检查都能自动缩小。好的守卫函数是一份可复用的类型知识。

  • typeof / instanceof / in 是三大内置缩小手段
  • 自定义守卫:返回类型写 x is T,缩小逻辑可复用
  • switch 对字面量联合(type 字段)也能缩小,且支持穷尽检查
TS
type Fish = { swim: () => void };
type Bird = { fly: () => void };

// 自定义类型守卫
function isFish(x: Fish | Bird): x is Fish {
  return typeof (x as Fish).swim === 'function';
}

function move(animal: Fish | Bird) {
  if (isFish(animal)) {
    animal.swim();      // ✓ 缩小为 Fish
  } else {
    animal.fly();       // ✓ 缩小为 Bird
  }
}

// in 操作符按结构区分
function getLen(x: string | string[]) {
  // string 与 string[] 都有 length,公共方法可直接用
  return x.length;
}

// switch + 字面量联合:穷尽检查
type Status2 = 'on' | 'off';
function label(s: Status2) {
  switch (s) {
    case 'on': return '开';
    case 'off': return '关';
  }
}
JS
// 自定义守卫编译成普通布尔函数
function isFish(x) {
  return typeof x.swim === 'function';
}
function move(animal) {
  if (isFish(animal)) animal.swim();
  else animal.fly();
}
move({ swim: () => console.log('游泳') });
move({ fly: () => console.log('飞') });
本节要点缩小 = 按条件收窄类型;`x is T` 守卫把判断逻辑变成可复用的类型知识。
🔗 相关词条JavaScript原型链React