You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中in二元运算符除映射类型外的其他用法咨询

TypeScript中in二元运算符的其他用法

除了你提到的在映射类型中遍历keyof返回的联合类型,in在TypeScript里还有两种常见用法:

  • 类型守卫:检查对象属性存在性
    在条件判断逻辑中,in可以作为类型守卫,帮你缩小变量的类型范围。当你用'属性名' in 对象的形式判断时,TypeScript会自动推断出符合该属性的类型分支:
type Cat = { meow: () => void };
type Dog = { bark: () => void };

function makeSound(animal: Cat | Dog) {
  if ('meow' in animal) {
    animal.meow(); // 此处animal被推断为Cat类型
  } else {
    animal.bark(); // 此处animal被推断为Dog类型
  }
}
  • 枚举成员有效性检查
    你可以用in判断一个值是否属于某个枚举的成员:
enum Fruit {
  Apple,
  Banana,
  Orange
}

function isFruit(value: number): value is Fruit {
  return value in Fruit;
}

以上用法的详细说明可参考TypeScript官方文档的类型守卫与枚举相关章节。

内容的提问来源于stack exchange,提问作者NeoZoom.lua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:07:03