首页 > 解决方案 > 从枚举的 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),
  ];
}

标签: typescript

解决方案


推荐阅读