Can you provide guidance on how to compare Enums in TypeScript?

Recently, the enum in my jhipster project went through a change. It was originally defined like this:

export enum DeclarationStatus {
  NEW = 'NEW',
  DRAFT = 'DRAFT',
  APPROVED_BY_FREELANCER = 'APPROVED_BY_FREELANCER',
  APPROVED_BY_CLIENT = 'APPROVED_BY_CLIENT',
  APPROVED = 'APPROVED'
}

and then changed to this:

export enum DeclarationStatus {
  NEW,
  DRAFT,
  APPROVED_BY_FREELANCER,
  APPROVED_BY_CLIENT,
  APPROVED
}

Initially, I could compare the status like this:

status === DeclarationStatus.APPROVED_BY_FREELANCER;

However, with the new change, that approach no longer works as the enum is now assigned numbers. The following comparison does produce the desired result:

DeclarationStatus[''+status] === DeclarationStatus.APPROVED_BY_FREELANCER;

Hence, my question is which method is better or if there might be a third alternative?


I marked this question as answered because the Jhipster community reverted the change back to the original state. This made the comparisons easier once again.

A special thank you to @vicpermir for facilitating this solution.

Answer №1

A common issue in this scenario is the lack of initialization for string enums. If your enums are not declared as const, you can still conduct a similar comparison using an alternative method.

status === DeclarationStatus[DeclarationStatus.APPROVED_BY_FREELANCER];

To elaborate, the following approach should yield the desired results:

enum Initialized {
    A = 'A',
    B = 'B'
}

enum NotInitialized { 
    A,                
    B                 
}

status = 'A';

// String enum initialized
let test1 = (status === Initialized.A); // true

// String enum not initialized
let test2 = (status === NotInitialized.A); // false
let test3 = (status === NotInitialized[NotInitialized.A]); // true :)

In a recent update to the JHipster Generator repository, a fix was implemented via pull request (PR#11218) specifically addressing this issue for React and enforcing the initialization of string enums within the generator.

Furthermore, according to the JDL documentation, it is possible to explicitly initialize enums:

enum DeclarationStatus {
   NEW (NEW),
   DRAFT (DRAFT)
}

For additional insights on TypeScript Enums, refer to the official documentation available here.

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

Ensuring that the field remains active in Angular2 even after editing it with a value

When the 3rd dropdown value is selected in the first field dropdown, it enables the 2nd field. However, when I edit and change a different value, since the 2nd field is disabled, I receive null or undefined as the value. I want the 2nd field to retain its ...

Guide to making API calls within the matcher function of Angular 7 routes

Currently, I am working on an Angular 7 project that involves a route matcher function. My goal is to make an API call to retrieve an array and then check if that array contains a specific URL slug. My Attempts So Far: I attempted to call the API using AP ...

Utilizing interpolation for a CSS class defined in an external file within Angular 2

Is it feasible to send a variable to a CSS class in an external CSS file within Angular 2, such as: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', sty ...

Use a pipe to show the content of the md-input

In my Angular 2 Material application, I have a form that includes a price input: <md-input [(ngModel)]="price" placeholder="Price"> </md-input>{{price|customCurrency}} This input field uses a custom version of the CurrencyPipe which you c ...

What is the best way to transform a JavaScript object into an array?

Here is the information I have: {product_quantity: {quantity: 13, code: "AAA", warehouse: "1000",}} The product_quantity field is part of a JSON object in a MongoDB database. I am looking to convert it into this format: {"produ ...

A guide on creating a LoopBack 4 REST API to fetch data from a MySQL database

I am currently diving into the world of Loopback 4. I have successfully created a model, repository, and datasource in connection with MySQL. This has enabled me to retrieve results from http://127.0.0.1:3000/myapi/{id}. In my initial setup, obtaining dat ...

Unable to loop through array generated by service - potential async complication?

In my service, I am populating an array of items by calling a function like this: items: IItem[] = []; ... LoadItems() { this.GetItems().subscribe((res) => { // console.log(res); if (res.status == 200 && res.body. ...

Utilizing 'nestjs/jwt' for generating tokens with a unique secret tailored to each individual user

I'm currently in the process of generating a user token based on the user's secret during login. However, instead of utilizing a secret from the environment variables, my goal is to use a secret that is associated with a user object stored within ...

Trouble extracting and utilizing GraphQL queries in Typescript with relay-compiler

I attempted to utilize relay with the Typescript react starter, but I am encountering several problems. It appears that babel-plugin-relay is unable to detect the graphql statements extracted by the relay-compiler. Below is my compiler script: "relay": " ...

Activate the button when a checkbox within a looping structure is selected using Angular 5

As a relatively new Angular 5 user, I am working with a button that looks like this: <button *ngIf="type!='invoices' && this.action==='edit'" disabled (click)="genera(fields.termini)" class="ml-16 mat-raised-button mat-accen ...

Observe the task while returning - Firebase Functions

I am working on a Firebase Cloud Functions project where I need to run a scraping task within one of the functions. While the scraping is in progress, I also need to provide progress updates to the consumer. For example, informing them when the task is at ...

Show varying mat-options based on the selected value of another mat-select

When selecting a continent from the first mat-select, only the countries belonging to that continent should appear in the second mat-select options. For example, if Asia is chosen as the continent, only Asian countries should be displayed. <div class=&q ...

How can I transfer information from one page to another in Next.js 14 without displaying the data in the URL?

As a React Native developer working on a web app, I'm facing a challenge with passing data from one page to another in Next.js 14 without displaying the data in the URL. I have a specific app directory within my Next.js project. When I mention not sh ...

Leverage lodash operators within nested object properties

My data consists of an array of objects { "agent_name": "AgentName", "analytics": [ { "date": "Tue, 1 Aug 2021 00:00:00 GMT", "intents_count":[ { "coun ...

Encountering a TypeError in NextJS: "Uncaught window.fbq is not recognized as a function"

Trying to implement Facebook Pixel for event tracking on the client side within my NextJS app-router project. Following the instructions provided in the NextJS pixel repository: https://github.com/vercel/next.js/tree/canary/examples/with-facebook-pixel/ap ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue. ...

Jetbrains WebStorm has issued a caution about experimental support for decorators, noting that this feature is in a state of flux and may

No matter how long I've been searching, I can't seem to get rid of this warning even after setting the experimentalDecorators in my tsconfig file. I'm currently working on an Ionic project with Angular, using webstorm by JetBrains as my IDE. ...

The error message "result.subscribe is not a function" indicates that there was a problem

I encountered an issue with the following error message: Uncaught TypeError: result.subscribe is not a function Here's a screenshot of the error for reference: https://i.sstatic.net/yfhy0.png Despite attempting to handle the error, I'm still s ...

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...