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

Backdrop behind of Bootstrap modal located back of other page contents

I'm facing some challenges after transferring a website I developed locally to a live server. The modal windows are appearing behind other content on the live server, although they work perfectly fine on the local version. Despite my attempts to adju ...

The headers set in jQuery's $.ajaxSetup will be used for every ajaxRequest, even if they

Below are the parameters set for all ajax calls in the <head> of my document. (This is necessary to fix an iOS ajax bug referenced at $.ajaxSetup ({ cache: false, headers: { "cache-control": "no-cache" } }); I am wo ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...

When utilizing PHP Form Validation alongside Javascript, the validation process does not halt even if a

I have been grappling with creating a basic HTML form validation using Javascript After experimenting with various examples, I am still facing the issue of my index page loading upon clicking the button on the form. Despite including "return false" in wha ...

Ways to determine the specific content type within req.body?

Based on the information found at https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, it is stated that the body of a request can be one of the following types: ArrayBuffer Blob formData JSON text I am wondering if there is a way ...

Using the active class feature in React Router

Hey there! I've been working with react router v6 and using NavLink to move between components. I've been trying to figure out how to add a custom active class in NavLink, but the method I tried isn't working. Here is what I attempted: <N ...

Input must be either a 12-byte string, a 24-character hexadecimal string, or an integer

As a beginner in coding, I am struggling to understand and fix this issue. If anyone could lend a helping hand, I would be truly grateful. Error Message: BSONTypeError - Argument passed in must be a string of 12 bytes or a string of 24 hex characters or a ...

Modify the contents of three div elements by incorporating JavaScript and ajax techniques

Currently working with rails 4 and JavaScript, I am faced with the following dilemma: I want to be able to alter the content of 3 specific divs on my page by clicking a single button. The values in these divs are being created by a Ruby function located in ...

Using AJAX to pass the ID name when clicking in PHP

Currently, I am in the process of implementing an Ajax-driven filtered search system that consists of three distinct tabs. These tabs allow users to search by names, category, and location. I have successfully enabled searching when a user types a name int ...

What steps do I need to take for the function to accurately determine the return type?

class Foo { name: string; constructor({name}: {name: string}) { this.name = name; } } class Bar<T extends Foo> { foo: T; constructor({foo}: {foo: T}) { this.foo = foo; } } class CustomFoo extends Foo { xxx: string; constr ...

Is tsconfig.json necessary for JS libraries without TypeScript to include a .d.ts file when shipping?

I am currently in the process of creating a .d.ts file for an established JavaScript library that does not utilize the TypeScript compiler or include any TypeScript code. Should I include a tsconfig.json file in the library to ensure proper interpretation ...

Server side pagination in AngularJS allows for dynamic loading of data

I am currently facing issues with slow application performance when retrieving large data from the database using Spring MVC and REST. I would like to implement server-side pagination in AngularJS to load only a subset of records. Could anyone provide gu ...

"Encountering Devextreme Reactive Errors while navigating on the main client

Attempting to integrate Devextreme with Material Ui in my Typescript React app has been a challenge. Despite following the steps outlined in this documentation and installing all necessary packages, I am encountering issues. I have also installed Material ...

How can I use a button to save all changes made in a JqGrid checkbox column simultaneously?

In my jqgrid, there is a column named 'asistencia' which displays data from a database as checkboxes. These checkboxes are pre-checked based on the property formatoptions: {disabled : false}. I would like to implement a 'save' button th ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

Angular's Readonly component fails to display line breaks

I am currently developing an Angular application using C#. One issue I have encountered is with read-only components that display saved data from the database. For instance, when inputting text into a Textarea component, such as: hello there hello ...

Switch the style sheets after the content

How can I create a toggle effect on the :after property, switching between + and - each time the link is clicked? I've attempted to achieve this using JavaScript, CSS, and HTML, but the code only changes + to - and doesn't switch back when the l ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...