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

Angular中如何从字符串值获取Enum类型的枚举键而非字符串类型

问题根因

你遇到的报错本质是类型不匹配问题:

  • TypeScript 中 Object.keys() 方法的返回值固定为 string[] 类型,因此你拿到的 enumKey 类型为通用 string,不是枚举 Widgets 的键的联合类型 'Foo' | 'Bar'
  • 枚举默认只允许用自身键的字面量类型作为索引访问属性,通用字符串类型无法通过类型检查。

解决方案

方案1:直接类型断言(最简写法)

将拿到的 enumKey 直接断言为枚举的键类型即可:

enum Widgets {
  Foo = "this is foo",
  Bar = "this is bar"
}

const current = "this is foo";
// 断言为 keyof typeof Widgets,也就是 'Foo'|'Bar' 联合类型
let enumKey = Object.keys(Widgets)[Object.values(Widgets).indexOf(current)] as keyof typeof Widgets;

console.log(Widgets[enumKey]); // 正常输出 "this is foo"

方案2:封装类型安全的通用工具函数(推荐,适合复用)

如果需要频繁做枚举值转枚举键的操作,可以封装泛型工具函数,不需要每次手写断言,还能兼容值不存在的异常场景:

enum Widgets {
  Foo = "this is foo",
  Bar = "this is bar"
}

// 泛型工具函数:传入枚举对象和枚举值,返回对应的枚举键,找不到则返回undefined
function getEnumKeyByValue<T extends Record<string, string | number>>(
  enumObj: T, 
  targetValue: T[keyof T]
): keyof T | undefined {
  const entry = Object.entries(enumObj).find(([_, value]) => value === targetValue);
  return entry ? entry[0] as keyof T : undefined;
}

const current = "this is foo";
const enumKey = getEnumKeyByValue(Widgets, current);
// 可选:加一层判断避免找不到值的运行时异常
if (enumKey) {
  console.log(Widgets[enumKey]); // 正常输出 "this is foo"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:12:01