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

如何在TypeScript中通过枚举值获取枚举键

解决方案

1. 从枚举值反向获取对应的键

TypeScript的字符串枚举不会自动生成反向映射(数字枚举默认支持),所以需要手动构建反向映射关系:

export enum A {
    Document = '1',
    Person = '2',
    Organization = '3',
    Equipment = '4',
    Location = '5',
    Event = '6',
    Link = '7',
    Target = '8',
}

// 构建值到键的反向映射对象
const reverseAMap = Object.fromEntries(
    Object.entries(A).map(([key, value]) => [value, key])
);

// 调用示例:通过'3'获取键'Organization'
const targetKey = reverseAMap['3']; // 结果为 'Organization'

2. 实现英文键到中文的翻译

创建一个中文映射表,将枚举键与对应中文关联:

const aChineseTranslator: Record<keyof typeof A, string> = {
    Document: '文档',
    Person: '人员',
    Organization: '组织',
    Equipment: '设备',
    Location: '地点',
    Event: '事件',
    Link: '链接',
    Target: '目标',
};

// 组合调用:通过枚举值直接获取中文翻译
const chineseResult = aChineseTranslator[reverseAMap['3'] as keyof typeof A]; // 结果为 '组织'

3. 封装为便捷工具函数(可选)

如果需要频繁使用,可以封装成复用函数:

function getAChineseByValue(value: string): string | undefined {
    const matchedKey = reverseAMap[value];
    if (!matchedKey) return undefined;
    return aChineseTranslator[matchedKey as keyof typeof A];
}

// 使用示例
console.log(getAChineseByValue('3')); // 输出 '组织'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 03:54:15