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

What could be causing the array to display incorrect results in React?

Showing below is a snapshot of my VScode. In this code snippet, I am declaring arr1 as an array consisting of numbers and then performing a reverse operation on it. Click here for input. The issue I am encountering is that the first paragraph in the outpu ...

Exploring the possibilities of implementing Undo and Redo features in freehand drawing with Reactjs on

After attempting to create a Freehand drawing using HTML5 canvas with React, my next step is to incorporate an undo and redo functionality when the corresponding buttons are clicked. I would greatly appreciate any assistance provided. function App(props) ...

Removing div elements containing specific text using jQuery

Hello everyone, I am trying to remove all divs that contain a specific part of a string. Does anyone know how I can do this? This is what my original HTML looks like: <div class="article-options_4"></div> And this is the new HTML structure, ...

How to Use C#'s Newtonsoft.Json Library to Retrieve a Name from a JSON

I have the following JSON data and I am utilizing Json.NET (Newtonsoft.Json): { "total_items": "62", "page_number": "6", "page_size": "10", "page_count": "7", "cars": { "car": [ { "car_name": "Honda", "engines": { ...

Utilizing TypeScript to define React interfaces

How can I effectively utilize two interfaces for the same object? For instance: interface interfaceOne { id: string color: string } interface interfaceTwo { id: string numb: number } I have an Item component that is designed to receive an item ob ...

Is it more efficient to use Vue events or Vuex for transmitting data between components?

Working on a project where data needs to be shared between components in order to update a canvas element at 30-60fps for optimal performance on low-end devices. Currently utilizing Vuex store/get method for data transfer, but considering using events as ...

Exploring the power of async/await in combination with map or foreach

I am facing a challenge in retrieving multiple product prices from my database. I had initially thought of using the map or forEach methods to iterate through them and add up the prices to a variable as shown below: // Get Total exports.getTotal = (req,re ...

The Uib-Dropdown functionality is not functioning properly when placed within the body of an HTML view

After correctly installing the following dependencies: "ui-bootstrap": "0.12.2", "ngAnimate": "1.5.5", "AngularJs": "1.5.5 I encountered an issue with creating a dropdown menu in my HTML view. Despite no visible errors and successful implementati ...

Unable to retrieve scope variable within AJAX call

I am currently in the process of running a loop function that contains an AJAX request within it. However, I am facing difficulties with the success function on the AJAX not being able to access a counter variable outside of the loop function. var upda ...

Create a Typescript React class and define the State type as either an interface or null

When working with React and typescript, it is common to declare state types in the following manner: import * as React from "react" interface IState { someState: string } class MyClass extends React.Component<{}, IState> { state = { someSt ...

A pale tooltip with a light arrow appearing against a soft white backdrop

Can someone help me figure out how to display a white tooltip with a white arrow? I've tried to implement it using the code below, but the white color is not visible against the background. Any suggestions on making it stand out? $(function () { ...

Mono repo project utilizing Angular 4+ and Typescript, enhanced with Bootstrap styling

Looking for a project to practice with Angular 4+ using Typescript and a Bootstrap template. Hoping for a setup where I can just run npm install and ng serve to start. Any recommendations for mono repos would be highly valued! ...

Is it possible to overlook specific attributes when constructing an object using TypeScript interfaces?

I have defined an interface with various properties. I am looking to instantiate an object based on this interface, but I only want to partially initialize some of the properties. Is there a way to accomplish this? Thank you. export interface Campaign { ...

Leveraging Angular to retrieve images from Google Feed API

I'm currently working on developing an RSS reader and trying to integrate images from the Google Feed API. While I have successfully extracted the publishedDate and contentSnippet, I am facing difficulty in getting the image src. The code snippets bel ...

Why does jQuery val() function fail to clear readonly input date in Firefox but succeed in Chrome?

When using JQuery.val(''), I noticed a difference in behavior between Firefox and Chrome. You can see the issue demonstrated in this jsfiddle: https://jsfiddle.net/mdqfbj/d4eovkg8/3/ A JS function triggered by a radio button is supposed to clea ...

Investigating issues with console errors and variables within callback functions in Angular 2 unit tests using Jasmine

I need assistance in achieving full coverage for this simple function, but I am struggling to do so. name-list.service.ts import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable ...

An essential aspect of utilizing ngrx is understanding how to access the previous and current state to effectively compare them when subscribing to the store

Within my component, I am subscribing to the ngrx store for changes in a specific state. I need to implement a condition where if the current state is different from the previous state, then I should perform certain actions. Is there a way to retrieve the ...

Automated Submission and Online Posting of (Web Form) with JavaScript Script

Is there a way to automatically fill out the form on my webpage ( ) using a JavaScript function with specific parameters? The source code for the webpage can be found here: webpage sourcecode script enter image description here ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...

Performing a JSON array query on a JSON field in Laravel version 5.4

Within the users table, there is a JSON column named "agencies" that stores data in a simple array format like: [ "0eb2edf0-50cb-44ff-a0a6-b2a104a9dc12", "f7c748d4-8718-441e-aa69-91b890ead5ed" ], The JSON structure above is considered valid. However, whe ...