简体   繁体   中英

Typescript: Custom interface type using enum

I am working with categories with my API endpoint and so I have created this enum for it:

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

And now I want to use this to set an interface for the category attribute in my database.

interface for that:

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

How do I specify the category interface type to be either of the values defined in the enum?

Just put the enum name categories like this:

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

Here is a working demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM