Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a enum member be aliased in TypeScript?

I have a below enum in TypeScript:

enum RoleTypes {
  None,
  Admin,
  SuperAdmin
}

When I run the following code:

var roleName = RoleTypes[RoleTypes.SuperAdmin];

the value of the variable roleName is SuperAdmin.

Is it possible to change it to a custom name 'Super Administrator', and how do I do this?

like image 892
L.W Avatar asked May 14 '17 07:05

L.W


People also ask

How enum works in TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.

What is type alias in TypeScript?

In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name.

How to define enum in JavaScript?

The easiest way to define an enum would be to use Object. freeze() in combination with a plain object. This will ensure that the enum object cannot be mutated. const daysEnum = Object.


1 Answers

You can use a seperate object or array for this (Playground):

enum RoleTypes {
    None,
    Admin,
    SuperAdmin
}

let RoleTypesDisplay: { [index: number]: string } = {};
RoleTypesDisplay[RoleTypes.None] = "None";
RoleTypesDisplay[RoleTypes.Admin] = "Administrator";
RoleTypesDisplay[RoleTypes.SuperAdmin] = "Super Administrator";

var roleName = RoleTypesDisplay[RoleTypes.SuperAdmin];
alert(roleName);

// because RoleTypes is a number based enum that starts with 0 this is equals to 
RoleTypesDisplay = ["None", "Administrator", "Super Administrator"];

var roleName = RoleTypesDisplay[RoleTypes.SuperAdmin];
alert(roleName);
like image 50
Markus Avatar answered Sep 26 '22 19:09

Markus