如何使用 TypeScript 枚举值作为类型?

Posted

技术标签:

【中文标题】如何使用 TypeScript 枚举值作为类型?【英文标题】:How can I use a TypeScript enums values as type? 【发布时间】:2022-01-15 12:00:29 【问题描述】:

如何在ISupportedTemplateType 中使用打字稿枚举值作为templateTypeId 的类型。值是 1、2、3,我希望它是 templateTypeId 的类型

export enum ETemplateType 
  'Cover Letter' = 1,
  'Wire Instructions' = 2,
  'Amendment' = 3,


export interface ISupportedTemplateType 
  templateTypeId: number; // HOW CAN I USE ENUM HERE?
  templateTypeName: keyof typeof ETemplateType;

【问题讨论】:

【参考方案1】:

你只是......使用它:

export interface ISupportedTemplateType 
  templateTypeId: ETemplateType;
  templateTypeName: keyof typeof ETemplateType;

然后这工作正常:

// works
const obj: ISupportedTemplateType = 
    templateTypeId: ETemplateType['Cover Letter'],
    templateTypeName: 'Cover Letter'

Playground

【讨论】:

以上是关于如何使用 TypeScript 枚举值作为类型?的主要内容,如果未能解决你的问题,请参考以下文章