JavaScript/TypeScript中如何通过循环优雅实现双枚举对象映射?
如何简化两个枚举间的重复映射逻辑
你无法直接在对象字面量内部编写循环逻辑,但可以通过提前生成枚举间的映射对象来消除重复代码——因为你的两个枚举ProductType和ProductTypeSlugEndpointApi的成员名称完全一一对应,这是可以利用的关键特性。
方案一:预生成全局映射对象(推荐)
这种方式会在代码初始化时生成一次映射,后续函数调用直接读取,性能更优且维护成本低:
首先确保ProductTypeSlugEndpointApi包含默认值(你原代码中提到了Default但枚举里没有,需要补充):
export enum ProductTypeSlugEndpointApi { CreditCard = 'cartoes-de-credito', PersonalLoan = 'emprestimos', RealStateFinancing = 'financiamentos-imobiliarios', AutoLoan = 'financiamentos-veiculos', BankAccount = 'contas', BusinessLoan = 'emprestimos-pjs', Broker = 'corretoras', CardMachine = 'maquinas-cartoes', CryptoBroker = 'corretoras-criptomoedas', Default = 'default-endpoint' // 补充默认值 }
然后生成映射并简化函数:
// 预生成映射对象,仅初始化一次 const productEndpointMap: Record<ProductType, ProductTypeSlugEndpointApi> = Object.fromEntries( // 过滤掉TypeScript枚举编译后的数字反向键 Object.keys(ProductType).filter(key => isNaN(Number(key))).map(key => { const enumKey = key as keyof typeof ProductType; return [ProductType[enumKey], ProductTypeSlugEndpointApi[enumKey]]; }) ) as Record<ProductType, ProductTypeSlugEndpointApi>; function MappingProductTypeToEndpointApi(type: ProductType) { return productEndpointMap[type] || ProductTypeSlugEndpointApi.Default; }
方案二:函数内动态匹配成员名称
如果不想预生成全局对象,也可以在函数内部通过枚举值反向查找成员名称,再匹配另一个枚举:
function MappingProductTypeToEndpointApi(type: ProductType) { // 根据枚举值反向获取对应的成员名称 const enumMemberName = Object.keys(ProductType).find( key => ProductType[key as keyof typeof ProductType] === type ) as keyof typeof ProductTypeSlugEndpointApi; return ProductTypeSlugEndpointApi[enumMemberName] || ProductTypeSlugEndpointApi.Default; }
优化优势
- 无需手动维护重复的键值对,新增枚举成员时,只要两个枚举的成员名称保持一致,映射会自动生效
- 代码更简洁,减少了人为出错的概率
- 方案一的预生成方式在多次调用函数时性能更稳定
内容的提问来源于stack exchange,提问作者Renan Bessa
相关产品推荐
相关产品推荐

