[英]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:解释:
typeof
on an enum
gives a type with each of its string members as keys and numbers as values.enum
上使用typeof
会给出一个类型,其每个字符串成员作为键和数字作为值。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
的映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.