Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum.

Imagine you have the following:

enum Gender {
    Male = 1,
    Female = 2
}

If you write:

for (let gender in Gender) {
    console.log(gender)
}

You will notice that it iterates over the enum 4 times. Initially displaying the string representations of 1 and 2, followed by printing the strings Male and Female.

I can only assume that this behavior is intentional. But my question remains - what is the rationale behind this somewhat unusual approach?

Answer №1

Although JS does not have native support for enums, TypeScript compiles your enum to:

var Gender;
(function (Gender) {
    Gender[Gender["Male"] = 1] = "Male";
    Gender[Gender["Female"] = 2] = "Female";
})(Gender || (Gender = {}));

This results in the enum having 4 keys (1, 2, Male, Female).

You can use this website to check the TypeScript to JavaScript compilation output.

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

Creating a Jest TypeScript mock for Axios

Within a class, I have the following method: import axios from 'axios' public async getData() { const resp = await axios.get(Endpoints.DATA.URL) return resp.data } My aim is to create a Jest test that performs the following actions: jes ...

Tips on utilizing a connected service in a custom Azure DevOps extension's index.ts file

I have created a unique extension for Azure DevOps that includes a specialized Connected Service and Build task. When setting up the task through the pipeline visual designer, I am able to utilize the Connected Service to choose a service and then populate ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

Facing an ESIDIR error in NextJs, despite the fact that the code was sourced from the official documentation

For an upcoming interview, I decided to dive into learning Next.js by following the tutorial provided on Next.js official website. Everything was going smoothly until I reached this particular section that focused on implementing getStaticProps. Followin ...

API requests seem to be failing on the server side, yet they are functioning properly when made through the browser

My current project involves utilizing an API that provides detailed information about countries. I've set up an express server to handle requests to this API, but for some reason it's not making the request. Interestingly, when I directly access ...

Leveraging the useContext and useReducer hooks within NextJS, while encountering the scenario of reading null

Trying to develop a tic-tac-toe game in NextJS and setting up a board context for my components to access. However, after integrating a reducer into the Wrapper to handle a more complex state, I'm encountering a null error. Errors: TypeError: Cannot r ...

ReactJS bug: Array rendering problem affected by recent changes

Why does ReactJS remove the first element instead of the middle element when using array.splice to remove an element from an array? This is my code. I am using Redux as well. const reducerNotesAndLogin = (state = initialState, action) => { var tableNo ...

Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty. Below is the query I am attempting to execute: con. ...

Tips for sorting multiple rows based on the primary column in MUI DataGrid ReactJS

https://i.stack.imgur.com/T9ODr.png Is there a way to utilize Material UI DataGrid to build a table that matches the structure displayed in the linked image? I have successfully created a basic table with DataGrid, but I'm struggling to add multiple ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

What is the value of x in the equation 2 raised to the power of x equals 800

Similar Question: What is the reverse of Math.pow in JavaScript? 2^x=i If i is given, how can we determine x using Javascript? ...

Tips for generating a subprocess with exec within a TypeScript Class

I am looking to automate the process of creating MRs in GitLab. When a button is clicked in my React/Typescript UI, I want to trigger command-line code execution within my Typescript class to clone a repository. However, every time I attempt to use exec, I ...

Setting an if isset statement below can be achieved by checking if the variable

I have included a javascript function below that is designed to display specific messages once a file finishes uploading: function stopImageUpload(success){ var imagename = <?php echo json_encode($imagename); ?>; var result = '& ...

The issue with AngularJS multiple $http requests failing to fetch accurate data

I'm having issues with my AngularJS controller and service modules. I want to refresh custController.allCustomers after adding a new customer so that the UI displays the new data. However, when I call custController.createCustomer, the new customer do ...

Utilizing the `this` keyword within a click handler that is passed through an intermediary function

If I initially have a click event handler in jQuery set up like this jQuery('#btn').click(_eventHandler); And handling the event as follows function _eventHandler(e){ jQuery(this).text('Clicked'); } Does the this keyword serve a ...

Tips on handling a Vue computed property

I am struggling to dispatch an object that is created within a computed property in vue.js. Being fairly new to this framework, I can't seem to make it work. My goal is to dispatch the object named "updateObject" to the vuex-store. I have tried using ...

Javascript malfunctions upon refreshing the div

After updating data with an ajax function and refreshing the div, I encountered an issue where the jQuery elements inside the div break. How can this be resolved? function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]&apo ...

Support for Arabic in database, PHP, and JavaScript

After inputting an Arabic comment into a textarea on the site, it displays correctly as "عربي" and is successfully sent to the database. However, upon refreshing the page, the text appears garbled: "عربÙ�". I attempted to directly enter s ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...