【问题标题】:TypeScript : how to declare an enum across multiple files?TypeScript:如何跨多个文件声明一个枚举?
【发布时间】:2016-07-14 16:30:19
【问题描述】:

文件 AppActions.ts

export enum Actions {
  START = 0,
  RECOVER,
  FIRST_RUN,
  ALERT_NETWORK,
  LOADING_DATA,
  RECEIVED_DATA,
  GO_OFFLINE,
  GO_ONLINE
}

文件 PlayerActions.ts

import {Actions} from "./AppActions.ts"
enum Actions {
  HEAL_SINGLE,
  HIT_SINGLE
}

通常,关于this manual,它应该在编译时抛出错误。但是:

1- PlayerActions.ts 似乎没有扩展现有的 Actions 枚举。 (在 WebStorm 中 import {Actions} from "./AppActions.ts" 为灰色)

2- 编译器不会抛出任何错误。

那么在多个文件中声明 Enum 的正确方法是什么?

【问题讨论】:

  • 您找到解决方案了吗?

标签: typescript enums


【解决方案1】:

在 Typescript 中似乎不可能有部分枚举,因为 Transpiler 为每个“导出”构建全局类型。

一种可能的解决方案可能是合并两个(多个)枚举,如下所示:

在您拥有的第一个文件中:

export enum Action_first_half{
   START = 0,
   RECOVER,
   ...
}

在另一个文件中:

export enum Action_second_half {
   HEAL_SINGLE,
   HIT_SINGLE
}

然后在另一个文件中,您可以:

const Actions = { ...Action_second_half , ...Action_first_half};
type Actions = typeof Actions ;

现在,您可以将“Actions”视为常规枚举:

public const action: Actions = Actions.START;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多