In TypeScript, it can be challenging to determine the equality between a value and an enum

I am encountering an issue with my simple code:

enum Color { BLUE, RED }

class Brush { 
    color: Color

    constructor(values) { 
        this.color = values.color
    }
}

let JSON_RESPONSE = `{"color": "BLUE"}`

let brush = new Brush(JSON.parse(JSON_RESPONSE))

When I try to check the color using:

console.log(brush.color === Color.BLUE)

The output is false.

I have attempted different variations like

brush.color === Color[Color.BLUE]

However, it resulted in a compiler error.

My question is how can I successfully compare two enums with the syntax enum === enum?

Answer №1

The issue at hand is that TypeScript's enums are essentially "named numeric constants."

As stated in the official TypeScript documentation on enums:

Enums permit the declaration of a collection of named numeric constants.

An enum consists of one or more members with corresponding numeric values . . .

A better alternative in this case would be to utilize string literal types:

type Color = "BLUE" | "RED";


Complete Code Example (Check out Demo):

type Color = "BLUE" | "RED";

class Brush { 
    color: Color

    constructor(values) { 
        this.color = values.color
    }
}

let JSON_RESPONSE = `{"color": "BLUE"}`

let brush = new Brush(JSON.parse(JSON_RESPONSE))

console.log(brush.color === "BLUE"); //=> true

Answer №2

A different approach (introduced since TS 2.4) is to use String enums:

enum Color {
  BLUE = "BLUE",
  RED = "RED"
}

console.log('BLUE' === Color.BLUE); // true

Since string enums do not have a reverse mapping (at least as of 2020), it might be wise to inline them using the const modifier.

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

Promise.all() ensures that all promises in the array are resolved with the same value

Currently, I'm in the process of developing a module that contains a function designed to return a promise using Promise.all() for the purpose of sending emails to multiple users. By simplifying the code, I have managed to isolate and reproduce the is ...

Issue with ActivatedRoute being empty when called in a Service in Angular version 2.0.2

I am interested in utilizing ActivatedRoute in a service to retrieve route parameters, similar to how it can be done in a Component. However, I have encountered an issue where the ActivatedRoute object injected into the Service does not contain the expecte ...

Having trouble with JSFIDDLE not functioning properly on my website

I'm having an issue with implementing a JSFIDDLE on my web form. The fiddle itself is working perfectly fine, but for some reason, I can't get it to work on my page. Can someone please help me figure out what mistake I might be making? Here is th ...

Nodemailer is experiencing difficulties when used within the routes directory

Recently, I encountered an issue with my subscribe form. It functions perfectly when called from app.js where the express server is defined. However, when I move subscribe.js to the routes folder and connect both files, it fails to send emails. Upon pressi ...

JavaScript - incorrect order for compiling

Is the user already in my SQLite database? If the user exists: return 500 (ERROR!!) If the user does not exist: return 200 (OK) This is my Node.js + Express script running on the server side. app.post('/adduser', function(req, res){ db.se ...

Using NgRx to observe state changes in a service instead of relying on an Effect

Is it possible for a service to monitor state changes and make HTTP calls based on the state value without being triggered by an effect (NgRx)? In other words, can a service react to a portion of the store and eliminate the need for an effect to be involve ...

``Why Ionic 3 Popover Sizes Should Adapt to Different Screen

Currently in my Ionic 3 project, I am utilizing a popover with a set height using the following code snippet: editOpty(rw){ let popover = this.editOptyPopup.create(EditOptyPopoverComponent, rw, { cssClass: 'edit-opty-popover'}); popover ...

HTML code displaying a fixed message at the top of the webpage

I'm working on a web page that has a lot of content. I need to have a message always visible at the bottom of the browser window, even when scrolling. Can anyone help me achieve this using simple CSS, HTML, jQuery, or PHP? Thanks! ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

Tips for choosing a dynamically generated ajax element

Question for you: I have a snippet of HTML code that looks like this: <li class='entry'> <div class='entryContent'> <p class='entryText'>Entry text></p> <a href="#" c ...

Identifying Changes with jQuery Event Listeners

I am trying to run some javascript code that is in the "onchange" attribute of an HTML element. For example: <input id="el" type="text" onchange="alert('test');" value="" /> Instead of using the onchange attribute, I want to trigger the e ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

Combine two arrays of data sources

mergeThreads() { const userId = this.auth.getUser().uid; const buyerThreads$ = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges(); const sellerThreads$ = this.afs.collection ...

Geoserver does not have the 'Access-Control-Allow-Origin' header

map.on('singleclick', function (evt) { document.getElementById('info').innerHTML = "Looks like you need to redo this :) !!!"; var view = map.getView(); var viewResolution = view.getResolution(); var source = hcm.getSource(); var url = s ...

Reactjs error: Invariant Violation - Two different nodes with the matching `data-reactid` of .0.5

I recently encountered a problem while working with Reactjs and the "contentEditable" or "edit" mode of html5. <div contenteditable="true"> <p data-reactid=".0.5">Reactjs</p> </div> Whenever I press Enter or Shift Enter to create ...

The React Native Expo is throwing an error stating that it is unable to locate the module 'minizlib'

At the instructions available in the read.me of https://github.com/react-community/create-react-native-app Upon selecting my template using the expo init command, I encountered the following error: Cannot find module 'minizlib' Error: Cannot fi ...

Master the Art of Animating Letters in the DOM by Navigating Through Any Array of Characters

I am attempting to implement a typewriter effect animation where a new message is displayed and animated as I type into an input box. Initially, I tried using a global char variable to iterate through each element of the array. However, whenever I passed ...

The concept of a singleton design pattern is like a hidden treasure waiting to be

My approach to implementing the singleton pattern in a typescript ( version 2.1.6 ) class is as follows: export class NotificationsViewModel { private _myService: NotificationService; private _myArray: []; private static _instance: Notificatio ...

Sending JSON data through an AJAX post request will not work

After struggling for hours trying to debug this issue on my own, I've come to the point of seeking assistance. I need to send a substantial amount of data to an ashx handler and here's how it looks: var value = [{"start":["3,0"],"block":["0,0", ...

Bidirectional data binding of JSON object in Angular

As a newcomer to Angular, I am currently working with Angular v.8 and have a JSON map in my component. My goal is to use this map to generate input fields in HTML, with the keys as field labels and values as input values. Although I have successfully itera ...