How to declare multiple enum in a single TypeScript file and return under single export statement (so that not exposing individual enums directly)

Viewed 60

I want to have multiple enums in the same file and export them under single export statement. and when I import this single file in another file, I can access any particular enum as required.

What I current have: 2 seperate .ts file for Actions and Groups enums,

First .ts file:

export enum Actions {
   Delete: "Delete",
   Update: "Update"
}

Second .ts file:

export enum Groups {
   Lead: "Lead",
   Permanent: "Permanent"
}

Expected: I want a single .ts file and a single export statement. Using this export, I can access my both the enums. something like: Enums.Actions or Enums.Groups.

Groups, Actions should only be accessed by Enums.Actions or Enums.Groups? some other file should not be able to access individual enums directly.

What is the suggested way to do this?

1 Answers

you can do it like this:

export namespace Enum {
  export enum Actions {
    Delete = "Delete",
    Update = "Update"
  }

  export enum Groups {
    Lead = "Lead",
    Permanent = "Permanent"
  }
}

How to use in a file:

import {Enum} from "../Enum"

We can access using Enum.Actions and Enum.Groups. Encapsulating enums in a namespace, allows Actions and Groups to not directly get accessed from outside.

Related