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

在TypeScript中从枚举生成带后缀字符串的联合类型

解决枚举翻译键的TypeScript类型定义问题

你需要把类型定义改成精确匹配枚举值拼接_one和_other的格式,而不是宽泛的DayType | string。直接用模板字符串类型就能实现这个需求:

enum DayType {
  BusinessDay = 'BUSINESS_DAY',
  CalendarDay = 'CALENDAR_DAY'
}

// 生成枚举值+"_one"和+"_other"的联合类型
type DayTranslationKey = `${DayType}_one` | `${DayType}_other`;

type SettingTranslations = {
  day_type: {
    [key in DayTranslationKey]: string;
  };
};

这样定义后,day_type的键就被严格限制为:

  • BUSINESS_DAY_one
  • BUSINESS_DAY_other
  • CALENDAR_DAY_one
  • CALENDAR_DAY_other

完全匹配你实际使用的翻译键格式,同时还能获得TypeScript的类型检查——如果键名写错(比如写成BUSINESS_DAY_single),编辑器会直接报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:01:49