Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript : how to declare an enum across multiple files?

file AppActions.ts

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

file PlayerActions.ts

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

Normally, regarding this manual it should throw an error at compile time. But:

1- the PlayerActions.ts does not seem to extend the existing Actions enum. (in WebStorm import {Actions} from "./AppActions.ts" is in grey)

2- the compiler does not throw any errors.

So what is the right way to declare Enum across multiple files?

like image 324
dagatsoin Avatar asked Jul 14 '16 16:07

dagatsoin


1 Answers

It doesn't seem to be possible to have partial enums in Typescript since the Transpiler builds the global types per each "export."

One possible solution might be merging two (multiple) enums as follows:

In the first file you have:

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

In another file you have:

export enum Action_second_half {
   HEAL_SINGLE,
   HIT_SINGLE
}

Then in another file, you can have:

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

Now, you can treat the "Actions" as if it is a regular enum:

public const action: Actions = Actions.START;
like image 58
Hosein Nourani Avatar answered Sep 18 '22 05:09

Hosein Nourani