首页 > 解决方案 > Typescript:使用枚举的自定义接口类型

问题描述

我正在使用我的 API 端点处理类别,因此我enum为它创建了这个:

export enum categories {
  DESIGN = 'design',
  ART = 'art',
  WRITING = 'writing',
  PHOTOGRAPHY = 'photography',
  MUSIC = 'music',
  DIGITAL = 'digital',
  MEDIA = 'media'
}

现在我想用它来为category我的数据库中的属性设置一个接口。

interface为了那个原因 :

interface ProjectAttrs {
  user: string;
  title: string;
  description: string;
  category:   // <== I want it to be either of those values defined above
}

如何将类别接口类型指定为枚举中定义的任一值?

标签: javascriptnode.jstypescripttypesenums

解决方案


只需像这样输入枚举名称categories

interface ProjectAttrs {
  user: string;
  title: string;
  description: string;
  category: categories;
}

这是一个工作演示


推荐阅读