typescript - 从枚举的 const 创建联合类型
问题描述
给定以下模式,其中 const 从一组枚举创建:
enum ServiceKeys {
SERVICE1 = 'Service1',
SERVICE2 = 'Service2',
}
enum Service1Actions {
ADD = 1,
}
enum Service2Actions {
DELETE = 1,
}
const serviceActions = {
[ServiceKeys.SERVICE1]: Service1Actions,
[ServiceKeys.SERVICE2]: Service2Actions,
}
我想在 const 中生成一个所有枚举的联合类型,它相当于:
type AnyServiceAction = Service1Actions | Service2Actions;
最终目标是使用这种类型来创建配置。为了演示,我已将代码简化为最简单的形式,但这基本上是它应该如何工作的。当然,在其原始形式中,还有更多与指定操作相关联的属性。
class Entry {
public readonly action: AnyServiceAction | null;
constructor(action: AnyServiceAction = null) {
this.action = action;
}
}
所以配置是以这种方式构造的:
class Config {
public readonly [ServiceKeys.SERVICE1]: Entry[] = [
new Entry(serviceActions[ServiceKeys.SERVICE1].ADD),
];
}
解决方案
推荐阅读
- json - 我正在尝试将 ansible 输出格式化为 item1 - item2 而不是两个单独的项目列表
- javascript - 闪亮的 Toastui 日历:更改特定日期的日历背景颜色
- verilog - 如何创建一个数组来在测试台中存储整数?
- jquery - 如何计算同一类不同容器中的单个项目?
- c - 使用互斥体构建信号量
- dockerfile - 如何默认启用 JupyterLab 扩展管理器?
- apache-spark - 让 PySpark 每列值输出一个文件(重新分区/分区不工作)
- modal-dialog - 验证失败后摇 wx.Dialog
- c# - 计算精灵根据需要行进的距离和行进速度改变大小的速度
- bash - bash 变量作为命令:在执行前回显命令并将结果保存到变量中