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

TypeScript中根据一个枚举的键获取同键名枚举的对应值

实现结论

两个枚举拥有完全相同的键时,完全可以实现基于一个枚举的键获取另一个枚举的对应值,你当前代码无法正常工作的核心原因有两个:

  1. getKeyByValue函数返回值是宽泛的string类型,TypeScript无法确认该字符串是目标枚举的合法索引键,会报类型错误
  2. 你定义的HistoricalRatesEnpoints枚举存在拼写错误:ONE_WEKK和Ranges中的ONE_WEEK不匹配,会导致该键对应的值取到undefined

修正实现方案

第一步:先对齐两个枚举的键

首先修正拼写错误,保证两个枚举的键名、大小写完全一致:

export enum HistoricalRatesEndpoints {
  ONE_DAY = '1-day/15m',
  ONE_WEEK = '7-days/1h',
  ONE_MONTH = '1-month/1d',
  THREE_MONTHS = '3-months/1d',
  SIX_MONTHS = '6-months/1d',
  ONE_YEAR = '1-year/1d',
}

export enum Ranges {
  ONE_DAY = '1 day',
  ONE_WEEK = '1 week',
  ONE_MONTH = '1 month',
  THREE_MONTHS = '3 months',
  SIX_MONTHS = '6 months',
  ONE_YEAR = '1 year',
}

第二步:修正工具函数的返回类型

给getKeyByValue添加明确的类型标注,让它返回Ranges枚举的键类型,由于两个枚举键完全一致,该类型可以直接作为HistoricalRatesEndpoints的合法索引:

function getKeyByValue(value: Ranges): keyof typeof Ranges {
  const index = Object.values(Ranges).indexOf(value);
  const key = Object.keys(Ranges)[index] as keyof typeof Ranges;
  return key;
}

第三步:正常跨枚举取值

修改后即可直接通过Ranges枚举拿到的键,读取另一个枚举的对应值,全程有完整的类型校验:

const key = getKeyByValue(Ranges.ONE_DAY); // 类型为枚举键的联合类型
const endpoint = HistoricalRatesEndpoints[key]; // 正确返回 '1-day/15m',无类型报错

更稳妥的生产级实现

如果需要长期维护这段逻辑,更推荐显式定义映射关系,省去运行时遍历枚举查找键的开销,同时可以通过类型约束强制两个枚举的键始终保持一致:

// 提取统一的键类型,从编译层面保证两个枚举的键完全匹配
type RangeKey = keyof typeof Ranges;

// 显式定义Ranges到接口地址的映射,少键、错键会直接报编译错误
const rangeEndpointMap: Record<RangeKey, HistoricalRatesEndpoints> = {
  ONE_DAY: HistoricalRatesEndpoints.ONE_DAY,
  ONE_WEEK: HistoricalRatesEndpoints.ONE_WEEK,
  ONE_MONTH: HistoricalRatesEndpoints.ONE_MONTH,
  THREE_MONTHS: HistoricalRatesEndpoints.THREE_MONTHS,
  SIX_MONTHS: HistoricalRatesEndpoints.SIX_MONTHS,
  ONE_YEAR: HistoricalRatesEndpoints.ONE_YEAR,
}

// 封装取值方法,逻辑更直观
function getEndpointByRange(range: Ranges): HistoricalRatesEndpoints {
  const key = getKeyByValue(range);
  return rangeEndpointMap[key];
}

// 直接调用即可
const oneDayEndpoint = getEndpointByRange(Ranges.ONE_DAY);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 11:01:24