14

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?

4 Answers 4

11

Yes, simply create an alias using a quoted identifier

enum RoleTypes {
 None,
 Admin,
 SuperAdmin,
 'Super Administrator' = SuperAdmin 
}
Sign up to request clarification or add additional context in comments.

Comments

9

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);

Comments

9

As of TypeScript 2.4 you can assign string values directly to enum members

enum RoleTypes{
  None = "None",
  Admin = "Administrator",
  SuperAdmin = "Super Administrator"
}

Also see here

5 Comments

Not tried as it's not released. In typescript 2.4, what's the value of RoleTypes.None, 0 or 'None'?
I would like RoleTypes.None remains 0, and RoleTypes[RoleTypes.None] has value 'None'. or RoleTypes.SuperAdmin remains value 2 and RoleTypes[RoleTypes.SuperAdmin] has value 'Super Administrator'. Is it possible?
According to the commit in GH, you can have mixed types for enum, including int and string
what are you using this with? If you are using something like angular2 or vuejs you can use a pipe/filter as a temporary solution
@L.W You can always use next as TypeScript version (e.g. package.json) to try it out. Now next is already 2.5
4

Combining Markus's answer with Use Enum as restricted key type in Typescript, you can use eithers of the following syntaxes to constrain object keys

Either { [key in RoleTypes]: string } or Record<RoleTypes, string>

enum RoleTypes {
  None,
  Admin,
  SuperAdmin
}

let RoleTypesDisplay: Record<RoleTypes, string> = {
    [RoleTypes.None]: "None",
    [RoleTypes.Admin]: "Administrator",
    [RoleTypes.SuperAdmin]: "Super Admin",
};

var roleName = RoleTypesDisplay[RoleTypes.SuperAdmin];

console.log(roleName);

Demo in TS Playground

1 Comment

Is there an easy way to export the RoleTypesDisplay as a constant or static collection for re-use?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.