What causes the discrepancy in values displayed by enums in TypeScript when assigned integers in reverse order?

Recently diving into the world of TypeScript, I've been experimenting with different types in this language.

One interesting data type I played with is enums. Here's an example of code I used:

enum colors {red=1,green=0,blue,white}; 
console.log(colors[1]);

To my surprise, the console output was 'blue' instead of 'red'.

This got me thinking - what exactly happens when assigning values to enums in descending order? Can someone shed some light on this behavior?

Answer №1

When facing runtime ambiguity, it is wise to inspect the compiled JavaScript version of your TypeScript code.
In this instance:

var colors;
(function (colors) {
    colors[colors["red"] = 1] = "red";
    colors[colors["green"] = 0] = "green";
    colors[colors["blue"] = 1] = "blue";
    colors[colors["white"] = 2] = "white";
})(colors || (colors = {}));

The enum value associated with ordinal 1 is first set as red, then overwritten by blue.

If you wish to assign custom ordinals, you must specify them for all enum values:

enum colors { red=1, green=0, blue=2, white=3 }; 

This will result in the following compilation:

var colors;
(function (colors) {
    colors[colors["red"] = 1] = "red";
    colors[colors["green"] = 0] = "green";
    colors[colors["blue"] = 2] = "blue";
    colors[colors["white"] = 3] = "white";
})(colors || (colors = {}));

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

Navigate Formik Fields on a Map

Material UI text-fields are being used and validated with Formik. I am looking for a way to map items to avoid repetitive typing, but encountering difficulties in doing so. return ( <div> <Formik initialValues={{ email: '&a ...

Using InjectionToken within an Angular APP_INITIALIZER function

I am currently working on implementing an APP_INITIALIZER in my Angular 10 project. The factory function I'm using has multiple dependencies, one of which is an InjectionToken<string>. However, I have encountered an issue when trying to inject i ...

Learn how to implement React Redux using React Hooks and correctly use the useDispatch function while ensuring type-checking

I'm curious about the implementation of Redux with Typescript in a React App. I have set up type-checking on Reducer and I'm using useTypedSelector from react-redux. The only issue I have is with loose type-checking inside the case statements of ...

Insufficient attributes in TypeScript component for React application

Developing with React import {Input} from '@xxx/forms'; <Input label="account Name" name="account"/> Type Definition for input import React, { Ref } from 'react'; import { InputProps as UITKInputProps } from ...

Converting the following ngRx selector to a boolean return – a guide

I am currently using the following filter to retrieve a list of data within a specific date range. I have implemented logic in the component where I check the length of the list and assign True or False to a variable based on that. I am wondering if ther ...

Troubleshooting the Issue with Conditional Rendering in Nextjs & TypeScript

Struggling with rendering a component conditionally. I have a drawHelper variable and a function to toggle it between true and false. The component should render or not based on the initial value of drawHelper (false means it doesn't render, true mean ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

Best practice for saving a User object to the Request in a Nest.js middleware

Currently, in my nest.js application, I have implemented a middleware to authenticate Firebase tokens and map the user_id to my database. Within this middleware, I retrieve the user_id from Firebase, fetch the corresponding User object from the database, a ...

In Angular Google Maps, here's a step-by-step guide on how to zoom in

I am currently utilizing agm/core to showcase the coordinates of a map. Here is the code snippet I am using: <agm-map [latitude]="10.3207886" [longitude]="123.90250049999997"> <agm-marker [latitude]="10.3207886 [longitude]="123.90250049999997 ...

Unable to combine mui theme with emotion css prop

I recently made the switch from overwriting styles in my styles.css file with !important to using emotion css prop for implementing a dark theme in my web app. Below is the code snippet from App.tsx where I define my theme and utilize ThemeProvider: const ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...

Incorporate personalized No Data Available message in ngx-datatable

How can I customize the no data message for ngx-datatable? I want to avoid displaying the default message that comes with it. Here is what I have attempted so far: <div *ngIf="showTable"> <ngx-datatable [rows]="rows"> ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

Utilizing Express JS to Optimize JPEG File Loading with Cache Headers

I have been working on implementing Cache-Control for my static image files. I have successfully set this header for HTML and JS files: https://i.stack.imgur.com/9VuWl.png However, I am facing challenges with JPEG files: https://i.stack.imgur.com/p52jm. ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

Show the login form and accompanying controls in the center of the screen with Angular 6

Currently, I am working on developing a Reactive form using Angular 6. In my TypeScript file, I have successfully obtained the form instance along with form controls. The next step involves iterating through these form controls and displaying the user inpu ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

What steps should I take to resolve an unhandled promise error in a React TypeScript application while making an axios POST request?

I am currently working on a .tsx file to implement adding an enterprise feature. Although I can input data, clicking the submit button does not trigger any action. My application includes a page that has a button for adding a new enterprise. Upon clickin ...