Switching an Enum from one type to another in JavaScript

UPDATE

After reading a comment, I realized that Enum is not native to JavaScript but is actually part of TypeScript. I decided to keep the original title unchanged to help others who may also make the same mistake as me.


I am faced with a scenario where I have two enums that share the same keys but contain different values.

enum RowStates {
    editing = 0,
    sentToApproval,
    approved
    // ...
}

enum RowColors {
    editing = '#ffffff',
    sentToApproval = '#ffffcc',
    approved = '#ccffb3'
    // ...
}

As part of this scenario, I need to create a function for conversion:

function Convert(rowState) {
// What logic should be implemented here to determine and return the appropriate rowColor?
// While using a switch statement for rowState seems like a viable option, I wonder if there are other solutions available?
}

Answer №1

Enums in TypeScript offer a unique feature known as reverse mapping:

enum TableStatus {
    active = 1,
    inactive,
    archived
}

enum TableColors {
    active = '#00ff00',
    inactive = '#ff0000',
    archived = '#0000ff'
}

function mapColor(tableStatus: TableStatus) {
    return TableColors[TableStatus[tableStatus] as keyof typeof TableColors];
}

console.log(mapColor(TableStatus.inactive)); // outputs '#ff0000'

Answer №2

attempt

function Transform (rowStatus: RowStatuses): RowShades {
    return RowShades[RowStatuses[rowStatus]];
}

demonstration here

Revision

As poloapolo pointed out in a comment, in the current TS 4.5.2 version (and possibly in some earlier versions as well), this solution triggers a linter error

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof RowShades

we can handle it in the following way (an alternative to Robby's answer)

function Transform (rowStatus: RowStatuses): RowShades {
  return new Map(Object.entries(RowShades)).get(RowStatuses[rowStatus]) as RowShades
}

Both solutions provide a form of validation for cases where a key in RowStatuses does not exist in RowShades

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

Modify the getAttribute value if it is null

I'm currently working on a project where I need to compile the answers selected in a quiz into a document. However, I've encountered a roadblock when certain questions are skipped based on previous responses. This leads to an error message: Un ...

Use a combination of the reduce and map functions in JavaScript to transform a one-dimensional array into a multi-dimensional array

Below is an array containing mySQL results: [ {"eventId":"84","shootId":"72","clubEventId":"253","clubId":"7"}, {"eventId":"84","sh ...

The POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

The function element.innerHTML is invalid when trying to assign an object value as an option

Hey there! I'm currently working on a JavaScript project where I have an input that retrieves text from an array. Each option in the array needs to be linked to an object so I can utilize its attributes. const data = [ { name: "SIMPLES NACION ...

Is it feasible to display a message for a certain duration without using the alert() function upon clicking a button?

I'm working on a NEXT.JS project and I need to display a <p> element under my button for a specific duration before it disappears. I don't want to use the alert() function. Any suggestions on how to achieve this? ...

Merge corresponding elements from two arrays based on their indices

If I have two arrays of objects structured like this: var arr1 = [{name: 'Jay'}, {name: 'Bob'}]; var arr2 = [{age: 22}, {age: 30}]; I am looking to merge them into a combined array as follows: var arr3 = [{name: 'jay', age: ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...

"Error encountered when attempting to call the requestFocus() method on a Java applet from JavaScript

I'm encountering an issue with calling the requestFocus() method in JavaScript. Uncaught TypeError: Object #<HTMLAppletElement> has no method 'requestFocus' Below is my JavaScript code within the <head> tags: function onLoad() ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

Difficulty with the value binding issue on input text produced by *NgFor

When using *ngFor in Angular to loop over an array and generate input text elements bound to the values in the array, I'm encountering some issues. The value is not binding correctly when a user inputs something into the text field. I attempted to ru ...

What is the proper way to import the Database class from BetterSqlite3 in a TypeScript project?

I am currently working on code that utilizes better-sqlite3 and my goal is to convert it to typescript. The original javascript code includes the following relevant sections: import Database from "better-sqlite3"; /** * @param {string} filenam ...

AngularJS App disrupted due to Direct Link to URL containing route parameters

Having an issue with direct links to pages containing a parameter. While links from the page itself work, accessing the page directly or refreshing it causes it to break and not load anything. This problem is occurring within a blog application I am develo ...

Error encountered when executing MySQL query using Node.js

I am trying to use Node JS and MySQL to check if a user already exists in the database. I have included the code snippet below: var username = "RandomUsername"; var email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b093 ...

Codeigniter 3 and JQuery seamless refresh: A dynamic duo

I'm currently attempting to utilize the following code: setInterval(function() { $('#myDiv').load('contentToLoad.php');}, 5000); while working with CodeIgniter. My attempt so far has been: setInterval(function() { $('.image ...

Choose all checkboxes that have a certain identifier

Currently, I am developing a menu permission project using vue.js. Within this project, I have various submenus that are children of different menus. My objective is to automatically select all submenus under a selected menu when the user clicks on "select ...

When I log them out, Node.js express always manages to bail me out even when Object is not defined

While attempting to destructure an object in my express middleware: const verifyLoggedInStatus = (req, res, next) => { try { const token = req.cookies['jwt-auth'].token; console.log('token: ', token); req. ...

tips for closing mat select when clicked outside

When a user clicks on the cell, it should display the value. If the user clicks outside the cell, the input field will close and show the field value. I am facing an issue on how to implement this with mat select and mat date picker. Any suggestions? Than ...

Retrieving HTML content from Wikipedia's API using JavaScript

I am encountering an issue where every time I attempt to log data to my console, an error occurs. Could someone kindly point out what may be the problem with the code? My objective is to actually showcase the html content on a webpage. Below is the code ...

What steps can I take to redesign my React App in order to successfully send state to a component located on a separate route?

I am currently facing a challenge with restructuring my App in order to pass state via props from the SubmitProject Component to the Portfolio Component. The catch is that I still need to maintain separate paths for each component, such as /portfolio and / ...

Having an issue with Local Storage returning undefined

I've been working on a form to input values and show the data on a different page after submission. Below is my form: <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" hr ...