Exploring Typescript ENUMs

I need to save a list of alpha-numeric options as an ENUM in Typescript. Here is an example list:

 1.134/2394 x 3-xyz
 2.123/234 y 3-ery 
 3.345/99 t 4-red
 4.4.1hv 3 secondary
 5.2.51hv 3 secondary
 6.1.61hv 3 secondary

If anyone has thoughts on how to store these options in Typescript, I would greatly appreciate it.

Answer №1

Is this how you would approach it?

enum y {
    '1.134/2394 x 3-xyz' = 2,
    '2.123/234 y 3-ery',
}

console.log(y['2.123/234 y 3-ery'])
// Output: '3'

Answer №2

Essentially, in JavaScript, enums are represented as objects. When you define an enum, you have the option to access the object in different ways.

If your keys include alphanumeric characters and spaces, you cannot access them using a dot notation after the enum name - for example, StatusCode.Ok 2 will result in an error.

In your scenario, you can access the object either by the assigned number or the assigned key. It's up to you to choose how to access it. You can access it like this: StatusCode['OK'].

Here's an example to illustrate: Source

/*
enum StatusCodes {
  OK = 200,
    BadRequest = 400,
    Unauthorized,
    PaymentRequired,
    Forbidden,
    NotFound
};
*/

// The above enum is converted to the Javasscript object like this. 

var StatusCodes;
(function(StatusCodes) {
  StatusCodes[StatusCodes["OK"] = 200] = "OK";
  StatusCodes[StatusCodes["BadRequest"] = 400] = "BadRequest";
  StatusCodes[StatusCodes["Unauthorized"] = 401] = "Unauthorized";
  StatusCodes[StatusCodes["PaymentRequired"] = 402] = "PaymentRequired";
  StatusCodes[StatusCodes["Forbidden"] = 403] = "Forbidden";
  StatusCodes[StatusCodes["NotFound"] = 404] = "NotFound";
})(StatusCodes || (StatusCodes = {}));

// Ways to access the enum. 
console.log(StatusCodes.OK);
console.log(StatusCodes["OK"]);
console.log(StatusCodes["200"]);

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

What could be causing the issue of why the null check in JavaScript isn't functioning properly

function getProperty(property) { console.log(localStorage[property]) //Displays “null” if(localStorage[property] == null) { console.log('Null check') return false; } return localStorage[property]; } The log outputs "nu ...

Receive information from the server and display it on the front-end

Hello! I'm currently in the process of developing a video uploader for my website. So far, I've successfully been able to upload videos from the front-end (built with React.js) to the back-end public folder (using Node.js) through the POST method ...

What is the best way to extract individual words from a string based on a specified list of tokens?

I am currently working with a list of tokens used to create artificial Japanese words, which is represented by the following array: var syllables = ["chi","tsu","shi","ka","ki","ku","ke","ko","ta","te","to","sa","su","se","so","na","ni","nu","ne","no","ha ...

"Optimizing navigation with dynamic link routing in AngularJS

I am working on a list of apartments displayed using ng-repeat. I need each apartment to be a clickable link that directs the user to view more details about that specific apartment. However, I am facing an issue where the links are not being repeated dyna ...

Performing mathematical calculations using javascript

In my project, I'm utilizing HTML, CSS, and JavaScript to achieve the following: Dropdown menu for Category (Coffee Appliance) Dropdown menu for Product (Keurig Coffee Maker) Wattage: 1500kWh (auto-filled from Local Storage) Daily Energy Con ...

Understanding the process of parsing an array in form-data in Node.js

https://i.stack.imgur.com/FPhX1.png I'm currently facing an issue while trying to read the image above in Node.js. I am using Express.js and have attempted to debug req.body, but it is returning an empty object {}. Even though I am using app.use(bod ...

Error: Axios return value is undefined if user is not found by the function

Trying to retrieve error messages from Express server using Redux Toolkit has presented some challenges. When no user is found, an error message is sent with a status code. Postman works fine in getting the error response but encountering issues on the cli ...

Discovering which page the form was submitted from using xsl template

Incorporating code like <input type="hidden" value="contact-form-1" name="getpage"> into my form is something I'm interested in, as it allows me to retrieve the URL of the page from which the form was submitted. The challenge arises because the ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

The React-Big-Calendar Drag and Drop feature in the month view consistently drags events from the leftmost column

I'm seeking assistance with a bug I've encountered while using the big-react-calendar. The issue arises when dragging an event, as it consistently moves to the leftmost column regardless of mouse position. However, shifting the event to a differe ...

Peruse a spreadsheet for relevant information

I am currently facing an issue with a search bar that I implemented to filter through a table. However, for some reason, the filtering function does not seem to work on the tbody section of the table. The content in the tbody is generated dynamically usi ...

Dealing with a large amount of HTML content following an Ajax request: best practices

I'm currently using a method that works fine, but I can't stop thinking about whether there might be a better way to achieve the same result. The task at hand is to display a user profile in a modal box. When a user clicks on a button or link, a ...

Having trouble escaping single quotes in JSON.stringify when using a replacer function

I'm attempting to replace single quotation marks in the values of my JSON string with \' however, it seems to not be working when I try to use the replacer function. var myObj = { test: "'p'" } var re ...

Is there a way for mocha to conduct a recursive search within my `src` directory in order to find a specific

In my npm project, I want to replicate the structure used by Meteor: there is a source file called client.js and its corresponding test file named client.tests.js residing in the src/ directory. The tests should be executed with the npm test command. I am ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

Is there a way to delete added information using a trigger that has been inserted through ajax?

I created a function in jQuery and Ajax to add information from a separate PHP file to another file. Let's name the destination file "Homepage" and the file with the data "Template". Here is the function I used: var box = $('#infoPageContainer& ...

Unable to automatically populate the final two digits of the card expiration year in MUI React

I've been working on fixing the auto-fill feature in my expiration input field. It's supposed to automatically fill in the last 2 digits of the year, just YY. Even though I think I'm doing everything correctly, the auto-fill feature keeps u ...

Utilize dynamic components to load varying data sets multiple times

Is there a way to dynamically load a component multiple times and pass data based on certain values so that it will display with real-time information? I came across an example at the following link: In this example, there is a messageComponent with a "m ...

Activate the zoom feature in jquery mobile

I am looking to implement the standard zooming effect in jquery mobile for my iOS iPhone app using jqm 1.3.2. After attempting the following: <meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-s ...

How can I redirect the page in CodeIgniter after successfully validating?

Currently, I am utilizing CodeIgniter for my project's development and implementing field validation using Bootstrap validator. Although the Bootstrap validator is functioning properly, I am encountering an issue. Upon successful validation, I expect ...