简体   繁体   English

TypeScript:有没有办法使用枚举以编程方式构造接口

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

So I have an enum defined as this所以我有一个定义为这个的enum

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 ?鉴于它们之间存在一对一的映射,我想知道是否有办法基于enum生成此interface 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.enum上使用typeof会给出一个类型,其每个字符串成员作为键和数字作为值。
  • Using keyof on that type gives a union type containing each of those keys.在该类型上使用keyof会给出一个包含每个键的联合类型。
  • Record<K, V> is a mapping from type K to type V . Record<K, V>是从类型K到类型V的映射。

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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