Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below?

enum days { sun = 1, mon = 0, tues };

console.log(days[1]); // outputs tues // should output -- mon
console.log(days[0]); // outputs mon // should output -- sun

Furthermore, how can I achieve printing sun in this particular case? This situation is perplexing me. Kindly provide valid explanations only after testing the code and observing the results.

Answer №1

When working with typescript, the following code is used to define an enum:

enum days { sun = 1, mon = 0, tues };

The typescript code above will be compiled into the following javascript equivalent:

var days;
(function (days) {
    days[days["sun"] = 1] = "sun";
    days[days["mon"] = 0] = "mon";
    days[days["tues"] = 1] = "tues";
})(days || (days = {}));
;

The key line in this process is days[days["sun"] = 1] = "sun";

Breaking it down further:

  • This part ensures that calling days.sun will return a value of 1
  • It also sets the value at key 1 as "sun", meaning initially days[1] is set to "sun"

Similarly, days[days["mon"] = 0] = "mon";

  • Ensures that calling days.mon will give a value of 0
  • Sets the value at key 0 as "mon", thus days[0] will be "mon"

However, the third part days[days["tues"] = 1] = "tues";

Involves setting days["tues"] = 1 which:

  • Allows for calling days.tues and getting 1 as the value
  • Returns the value set at key "tues" as 1

With this operation, days[1] will be replaced with the value "tues"

Answer №2

Your enum structure is quite unique and not following the usual convention. According to the documentation, undefined enums will automatically assign a value by adding 1 to the previous value.

In your current enum setup, you have two values set to 1 which may cause unexpected behavior in Typescript/Javascript as it tends to choose the last item with the desired value.

Current code:

enum days{
sun = 1,
mon = 0,
tues
}

VS (a different enum from a functional project of mine)

enum days{
Sun = 0,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}

According to the documentation (https://www.typescriptlang.org/docs/handbook/enums.html)

If an enum member does not have an initializer and the preceding one was constant, the value of the current member will be the preceding value plus one. The first element of an enum without an initializer is assigned the value 0.

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

Using Typescript to mute audio elements within HTML documents

I have a scenario where I want to mute audio that automatically plays when the screen loads. In order to achieve this, I am attempting to add a button that can toggle the audio mute functionality using Typescript within an Angular4 application. The code sn ...

Arranging Objects by Alphabetical Order in Typescript

I am struggling with sorting a list of objects by a string property. The property values are in the format D1, D2 ... D10 ... DXX, always starting with a D followed by a number. However, when I attempt to sort the array using the following code snippet, it ...

The ListView is not updating correctly as expected

Currently, I am working on a project where I have a Page with a ListView that displays items from an ObservableArray of Expense objects. The issue I am facing is that when I scroll down, the amount property of some Expense rows is not being displayed. Howe ...

Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyu ...

Remove user from axios response interceptor for server-side component

In my Next.js 14 application, I have set up axios interceptors to handle errors. However, I need assistance in logging out the user and redirecting them to the '/login' page if any error occurs. Below is the code snippet for the interceptors: axi ...

Sweetalert seems to have hit a roadblock and is not functioning properly. An error has been detected in its TS file

Currently, I am responsible for maintaining an application that utilizes Angular 7.0.7 and Node 10.20.1. Everything was running smoothly until yesterday when my PC unexpectedly restarted. Upon trying to run ng serve, I encountered the following error: E ...

I have encountered limitations with useFormik where it does not accept null values for initialValues, even while utilizing a validationSchema

I am currently utilizing the useFormik hook to handle my form. The userId field is a select, so by default its value is set to null. However, my validationSchema requires this field to be populated before submission. const formik = useFormik<ApiCredit ...

What is the best way to reference class variables and methods within a callback function in Typescript?

While working on my Angular project with the Highcharts API, I encountered a situation where I needed to pass a state code to a class level method after drilling down to a specific map location. Below is the snippet of my current code: ngOnInit() { this. ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

A step-by-step guide on effectively adopting the strategy design pattern

Seeking guidance on the implementation of the strategy design pattern to ensure correctness. Consider a scenario where the class FormBuilder employs strategies from the following list in order to construct the form: SimpleFormStrategy ExtendedFormStrate ...

In the application I'm developing, I'm utilizing React alongside TypeScript, making use of the useContext and useReducer hooks. However, I've encountered an issue where the dispatch function is not being

Currently, I have implemented a feature where two lists are displayed as cards based on one main list of objects. The goal is to toggle the 'favorite' value for each card item when the star button is clicked. This action should move the favorited ...

Harnessing the Power of FormControlName and Labels in Angular 6

In my project using Angular 6 and reactive forms, I have a grid with a Detail button that opens a modal window displaying student information. However, when implementing the HTML for the dialog box as shown below, I encountered an error message stating: No ...

Working with dual generic parameters in a function

Here is a function I am using: bind<T, K extends keyof T>( data: T[], bindedData: T[], key: K, newKey: string ) { } I'm trying to use two generic parameters, but my attempt here did not work: bind<T, K extends keyof T> ...

Is there a way to determine if silent login is feasible with adaljs-angular4?

I'm currently utilizing the library [email protected] for an Angular 6 project. I am attempting to achieve the following: If a silent login (login without requiring user input) with Office365 is achievable, then perform a silent login (using ...

How can you specify the active route in Angular?

I am curious about whether it is possible to set the active route from a script instead of just from the HTML template. Let me provide an example: @Component({ template: `<input type="button" (click)="back()" value="back" ...

Could you please share the standard naming convention used for interfaces and classes in TypeScript?

Here's what I have: interface IUser { email: string password: string } class User { email: string password: string constructor(email: string, password: string) { this.email = email this.password = password } isEmailValid(): boo ...

Prevent using keys of nullable properties as method parameters in Typescript generics

What is the solution to disallow a method from accepting a parameter of type keyof this where the property is nullable? Consider the following example: abstract class MyAbstractClass { get<K extends keyof this>(key: K): this[K] { return this[k ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code snippet I tried, but it didn' ...

The validators in the FormControl are inconsistently functioning, showing up where they shouldn't and sometimes failing to work where

I am currently developing a dynamic form in Angular that allows users to request any number of parts, generating rows of input fields for each part. Each part has specific required fields, some of which should only accept numbers. I have implemented valid ...

webpack is having trouble locating the src file, even though it should not be searching for it in the first place

I'm currently delving into the world of using TypeScript with React and am following a helpful tutorial at: https://blog.logrocket.com/how-why-a-guide-to-using-typescript-with-react-fffb76c61614 However, when attempting to run the webpack command thr ...