dagatsoin
dagatsoin

Reputation: 2656

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?

Upvotes: 10

Views: 2099

Answers (2)

ruwan800
ruwan800

Reputation: 1885

You can declare your enum as a global value like below.

In the first file

    declare global {
      export enum Actions {
        START = 0,
        RECOVER = 1,
      }
    }

In the second file

    declare global {
      export enum Actions {
        HEAL_SINGLE = 2,
        HIT_SINGLE = 3,
      }
    }

Then you can simply access enum value like Actions.START or Actions.HEAL_SINGLE in any file

Upvotes: 0

Hosein Nourani
Hosein Nourani

Reputation: 21

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;

Upvotes: 1

Related Questions