Is there a way to create an alias for an enum member in TypeScript?

In my TypeScript code, I have an enum defined as:

enum RoleTypes {
  None,
  Admin,
  SuperAdmin
}

After running this code snippet:

var roleName = RoleTypes[RoleTypes.SuperAdmin];

I noticed that the variable roleName holds the value SuperAdmin.

Is there a way to change it to something custom like 'Super Administrator'? If so, how can I achieve this?

Answer №1

A method to implement this is by establishing an alias with a quoted identifier.

enum UserRoles {
 None,
 Manager,
 SuperManager,
 'Super Manager' = SuperManager
}

Answer №2

If you want to handle this situation, consider using a separate object or array like the following example (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);

// since RoleTypes is an enum based on numbers starting with 0, it can be represented as 
RoleTypesDisplay = ["None", "Administrator", "Super Administrator"];

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

Answer №3

With the release of TypeScript 2.4, it is now possible to directly assign string values to enum members.

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

For more information, check out this link

Answer №4

Mixing Markus's response with Using Enum as a restricted key type in Typescript, you have the option to employ either of the subsequent formats to limit 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);

View demonstration on TS Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery for Revealing or Concealing Combinations of Divs

UPDATE: Check out this answer. I have a complex query related to jQuery/JavaScript. I came across a post dealing with a similar issue here, but my code structure is different as it does not involve raw HTML or anchor tags. Essentially, I am working on ...

Is there a way to catch a downloaded file inside an iframe?

My dilemma involves an external site embedded in an iframe that contains a save button to download a json file. I am seeking a solution to capture the contents of this downloaded file within my own code. Is there a possible method for achieving this? Rese ...

Comparison between SSD and HDD animation speed in web hosting environments

I am currently in search of a web hosting provider for a website I have created. The site features some performance-heavy animations, particularly due to a fullscreen slider with filter and scaling transitions. I need a provider that can ensure optimal per ...

Do we need to use initializeApp() from Firebase 9 when setting up email login?

Similar Topic: Exploring the Fun of Firebase's initializeApp(config) Function When integrating Gmail login, is it necessary for an app to invoke intializeApp()? Although the documentation specifies that a config object must be provided to initializ ...

vue.runtime.esm.js?2b0e:619 [Vue warn]: The property or function "add" is being referenced in the render method but is not defined on the instance

enter code here <template> <div id="app"> <h1>Hello</h1> <button @click="add"></button> </div> </template> <script> export default { name: 'App', data(){ return{ method ...

Utilizing Google Maps and navigation features directly in the mobile application

I am currently working on an app with the Ionic framework and I'm looking to incorporate Google Maps and navigation directly into the app without having to redirect users to the Google Maps application. My development stack includes TypeScript, HTML, ...

Vue.js: Incorporating Multiple CSS Templates in a Single Application

As a beginner in Vuejs, I am trying to figure out how to incorporate multiple templates into one application. For example, I want to use the Flatkit template for my SignIn page and a different template (Dashboard) for the Admin dashboard. How can I integra ...

Using AngularJS, you can pass serialized objects as query string parameters

I'm trying to pass nested objects as query parameters from my AngularJS Controller using the following code: $scope.redirect = function () { const params = $httpParamSerializer({ initval: { user: { id: 1, ...

What is the best way to choose a single li element?

I am working on creating a reservation system using HTML, CSS, and JS. I want to customize the color of the border for each list item (li). However, I want only one li to be selected at a time. When I click on a different li, it should remove the selection ...

Tips on retrieving a strongly typed value from a method using Map<string, object>

Having had experience working with C# for a while, I recently ventured into a Node.js project using TypeScript V3.1.6. It was exciting to discover that TypeScript now supports generics, something I thought I would miss from my C# days. In my C# code, I ha ...

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

Determine the data type of a property by referencing the data type of another property within an array of objects using TypeScript

I am working with a specific type of interface called Route that consists of name and path properties. interface Route { name: string, path: string } const routes = [ { name: "first", path: "/first" }, ...

Troubleshooting: GSAP Scrolltrigger malfunctions when using multiple triggers

Having multiple triggers with different functionalities: Show or remove a canvas Change the background color of a section Play or pause video when in view Play or pause CSS animation The first two triggers work fine individually, but I am encountering an ...

Updating reactive form fields with patched observable data in Angular

Struggling with initializing a reactive form in my component's onInit() method, as well as handling data from a service to update or create entries in a MySQL table. The issue lies in using patchValue to pass the retrieved data into the form: compone ...

Recursive React Function for Rendering Components

I've been working on integrating a react-bootstrap component into a custom navBar component in my react project. I have a recursive function set up to render the components and drill down until there are no more NavItem components nested under the Nav ...

Encountered a DataTables warning: an Ajax error has occurred with table id=products. To gain a deeper understanding of this issue, kindly refer to http://datatables.net/

Whenever I run the script, an error message pops up saying "127.0.0.1:60809 DataTables warning: table id=products - Ajax error. If you need more information about this error, please visit http://datatables.net/tn/7". Here is the image of the error. The i ...

Clear function of signature pad not working inside Bootstrap modal dialogue box

Currently, I'm working on implementing a signature pad dialogue box using Bootstrap modal. When the user clicks on the "Complete Activity" button, a dialog box should pop up with options for yes or no. If the user selects yes, another dialog box shoul ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

What causes Array.prototype.sort to function differently in Chrome?

As I was attempting to organize an Array, I observed a discrepancy between the behavior in Chrome V79 and Firefox Dev Edition V72 (both desktop versions). Here is the test: console.log([4, 2, 5, 1, 3].sort((a, b) => a>b)); console.log(Array.prototy ...

How to count the keys of an object in JavaScript that use dot notation?

Looking to tally the arrays within a javascript object. This feedback is returned from Laravel validator. { "message":"The provided data was invalid.", "errors":{ "roomtype_id":[ "Please choose a room type" ], "pri ...