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

如何避免TypeScript中的枚举值冲突问题

如何避免不同枚举类型的枚举值冲突?

我的应用中存在大量枚举,部分不同类型的枚举拥有相同的枚举值。我编写了一个通用函数,接收任意枚举并尝试根据枚举类型和值进行处理,但当枚举键名相同时,会出现值冲突的问题。

问题示例

enum Car {
  bmw = "bmw",
  ferrari = "ferrari"
}

enum Brand {
  bmw = "bmw",
  ferrari = "ferrari"
}

function describeIt(it: string) {
  switch (it) {
    case Car.bmw:
      console.log("It's a BMW car");
      break
    case Brand.bmw:
      console.log("It's the BMW brand");
      break
    case Car.ferrari:
      console.log("It's a Ferrari car");
      break
    case Brand.ferrari:
      console.log("It's the Ferrari brand");
      break
  }
}

describeIt(Car.bmw)   // 输出:It's a BMW car,符合预期!
describeIt(Brand.bmw) // 输出:It's a BMW car,预期:It's the BMW brand

由于Car.bmw和Brand.bmw的字符串值完全相同,在switch判断中会优先匹配到第一个符合条件的case分支,导致无法区分枚举所属的类型,进而触发错误的逻辑。

核心需求:我不希望手动给枚举值添加类型前缀(比如Brand.bmw = "Brand.bmw"),需要从枚举类型本身出发找到解决方案,尽可能保持语法简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:23:15