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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With