简体   繁体   中英

TypeScript: is there a way to programatically construct an interface using an enum

So I have an enum defined as this

enum EventType {
  JOB,
  JOB_EXECUTION,
  JOB_GROUP
}

And I need to create an interface like this

interface EventConfigurations {
  JOB: {
    Enabled?: boolean;
  };

  JOB_EXECUTION: {
    Enabled?: boolean;
  };

  JOB_GROUP: {
    Enabled?: boolean;
  };
}

Given there is a one to one mapping existing between them, I wonder if there is a way to generate this interface based on the enum ? Currently I just hardcoded it

You can create it as a type (not an interface) like this:

type EventConfigurations = Record<keyof typeof EventType, { Enabled?: boolean }>

Explanation:

  • Using typeof on an enum gives a type with each of its string members as keys and numbers as values.
  • Using keyof on that type gives a union type containing each of those keys.
  • Record<K, V> is a mapping from type K to type V .

Playground

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