【问题标题】:What's best practice to make enums compatible in Typescript?在 Typescript 中使枚举兼容的最佳实践是什么?
【发布时间】:2021-09-03 07:35:19
【问题描述】:

我有 const 枚举,类似于:

const enum ComponentId {
    A = 0, 
    B, 
    C
}

我还有另一个常量枚举叫做 BaseId,它可以在多个地方共享,定义方式相同:

const enum BaseId {
    D = 100, 
    E, 
    F
}

问题是,我希望能够在使用 ComponentId 的地方也使用 BaseId:

function operateComponent(id: ComponentId) // want to be able to use BaseId as well

我应该只做 id: ComponentId | BasedId,但这样我需要在很多地方更改代码。我想知道实现这一目标的最佳做法是什么?

【问题讨论】:

  • check out this explanation of enums in TS - 如果在您的情况下这是一个可行的解决方案(没有上下文无法判断),您可以从 100 开始向 ComponentId 添加值,并完全忽略 BaseId跨度>

标签: typescript enums


【解决方案1】:

起初 - 你不需要在枚举附近使用const,因为它是 TS 构造,而不是变量

如果它为您解决了问题,请查看此示例:

您需要创建一个联合类型,它将包含两个或多个枚举:

enum ComponentId {
  A = 0,
  B,
  C,
}

enum BaseId {
  D = 100,
  E,
  F
}

type ComponentIdOrBaseId = ComponentId | BaseId

const operateComponent = (data: ComponentIdOrBaseId) => {}

const x = operateComponent(ComponentId.A)

另一种选择是将所有值组合在单个枚举中:

enum ComponentId {
  A = 0,
  B,
  C,
  D = 100,
  E,
  F
}

type ComponentIdOrBaseId = ComponentId

const operateComponent = (data: ComponentIdOrBaseId) => {}

const x = operateComponent(ComponentId.F)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多