如何在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
相关产品推荐
相关产品推荐

