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

如何在TypeScript中正确判断变量属于两个枚举中的哪一个?

解决TypeScript枚举类型守卫的类型不匹配问题

你遇到的错误源于Object.values(Animal)返回的类型是Animal[],而includes方法默认仅接受Animal类型参数,但你的函数参数是Animal | Bird,TypeScript的严格类型检查会阻止这种跨枚举的类型传递。以下是几种可行的修正方案:

方案1:给includes指定泛型

通过为includes显式指定泛型,允许它接收Animal | Bird类型的参数:

function isAnimal(type: Animal | Bird): type is Animal {
  return Object.values(Animal).includes<Animal | Bird>(type);
}

function isBird(type: Animal | Bird): type is Bird {
  return Object.values(Bird).includes<Animal | Bird>(type);
}

方案2:使用类型断言

将枚举值数组断言为包含两种枚举类型的联合数组,让includes支持联合类型参数:

function isAnimal(type: Animal | Bird): type is Animal {
  return (Object.values(Animal) as (Animal | Bird)[]).includes(type);
}

function isBird(type: Animal | Bird): type is Bird {
  return (Object.values(Bird) as (Animal | Bird)[]).includes(type);
}

方案3:直接枚举值判断(适合成员较少的枚举)

如果枚举成员数量不多,直接通过相等判断实现类型守卫,这种方式更直观且类型检查更严格:

function isAnimal(type: Animal | Bird): type is Animal {
  return type === Animal.CAT || type === Animal.DOG;
}

function isBird(type: Animal | Bird): type is Bird {
  return type === Bird.RAVEN || type === Bird.PIGEON;
}

额外建议:规范枚举成员使用

定义creatureList时,建议直接使用枚举成员而非字符串字面量,这样更符合TypeScript类型规范,避免潜在的类型不匹配问题:

const creatureList: Array<{
  type: Animal | Bird ;
  name: string;
}> = [
  {
    type: Animal.CAT,
    name: 'Mauricio',
  },
  {
    type: Bird.RAVEN,
    name: 'Jacob',
  },
]

内容的提问来源于stack exchange,提问作者Rex4r

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:41:26