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

Error in TypeScript React: 'Display' property is not compatible with index signature

My design page in React with TypeScript template is using Material UI, with custom styles implemented using the sx prop of Material UI. To customize the styling, I have created a separate object for the properties related to the sx props: const myStyles = ...

Setting up React Context API with TypeScript: A Step-by-Step Guide

I recently updated my app.js file to app.tsx for improved functionality. However, I encountered an error with the current value. app.tsx import React, { createContext, useState } from "react"; import SelectPage from "./pages/select/select& ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Unleashing the power of storytelling with React: A guide to creating dynamic story

weather.stories.ts export default { title: 'Widgets/Forecast', component: Weather, } const Template: Story<any> = (args) => <Weather {...args} />; export const Default = Template.bind({}); Default.args = { forecast: { ...

Rollup faces challenges when trying to bundle source code alongside Bazel and Typescript

I am attempting to create a bundle using rollup, typescript, and bazel environment. I am having trouble importing relative paths. Typescript builds correctly but rollup is unable to bundle the source. WORKSPACE # WORKSPACE workspace( name = "WORK ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

Missing expected property in TypeScript casting operation

I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results. class X { y: string; get hi(): string { ...

Is it possible to showcase a unique date for every item that gets added to a list?

I am new to using React, so please bear with me. I want to be able to show the date and time of each item that I add to my list (showing when it was added). I am struggling to get this functionality working with my current code. Any help or explanation o ...

Required Field Validation - Ensuring a Field is Mandatory Based on Property Length Exceeding 0

When dealing with a form that includes lists of countries and provinces, there are specific rules to follow: The country field/select must be filled out (required). If a user selects a country that has provinces, an API call will fetch the list of provinc ...

Can :[Interface] be considered a correct array declaration in Typescript?

My TypeScript codebase is filled with code snippets like the one below... export interface SomeType { name: string; } export interface SomeComposedType { things: [SomeType]; } Everything was working smoothly until I started experiencing issues su ...

Retrieving the value of a selected option in Angular

I have the following dropdown select in my HTML and I am currently retrieving the text content of the selected option. How can I access the value attribute instead? Here is the dropdown select: <form [formGroup]="angForm" class="form-inline my-5 my-l ...

I am experiencing difficulty in retrieving the content-disposition from the client

I am attempting to retrieve a .xlsx file that is generated on the backend using Spring Boot. I am able to retrieve headers on the frontend, which include the content-disposition as shown below. However, I am unable to access the content disposition in the ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

Establishing the initial state within the constructor of a React Component utilizing a generic state

I have encountered an issue with React and Typescript. I am working on a component that utilizes two generics for props and state. interface Props { foo: string; } interface State { bar: string; } class Foo< P extends Props = Props, S e ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

`In Vue.js, it is not possible to access a data property within a

I encountered an issue while attempting to utilize a property of my data within a computed method in the following manner: data() { return { ToDoItems: [ { id: uniqueId("todo-"), label: "Learn Vue", done: false }, ...

Aliases for NPM packages and TypeScript declaration files

I am in need of two separate versions of a package, and fortunately with npm 6.9.0 I can easily accomplish that now. My dilemma is this: the package comes with type definitions. However, when I create an alias for this package and refer to it using the al ...

What causes observables stream to be cancelled or stopped by my HTTP request?

I am facing an issue with adding a new property called Blobs to each application in an array of applications. I need to make a separate HTTP request to fetch Blobs for each application using the switchMap operator. However, the problem is that only the las ...