11

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?

L.W
  • 225
  • 1
  • 2
  • 12

4 Answers4

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

Community
  • 1
  • 1
Yaakov Ellis
  • 40,752
  • 27
  • 129
  • 174
  • Not tried as it's not released. In typescript 2.4, what's the value of RoleTypes.None, 0 or 'None'? – L.W May 14 '17 at 08:20
  • 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? – L.W May 14 '17 at 08:27
  • According to the commit in GH, you can have mixed types for enum, including int and string – Yaakov Ellis May 14 '17 at 08:31
  • 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 – Daniel Ormeño May 14 '17 at 08:47
  • 1
    @L.W You can always use `next` as TypeScript version (e.g. package.json) to try it out. Now `next` is already 2.5 – sebilasse Jun 14 '17 at 11:14
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);
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Markus
  • 3,871
  • 3
  • 23
  • 26
9

Yes, simply create an alias using a quoted identifier

enum RoleTypes {
 None,
 Admin,
 SuperAdmin,
 'Super Administrator' = SuperAdmin 
}
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
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

KyleMit
  • 30,350
  • 66
  • 462
  • 664