Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

281
Views
Comparing value to enum isn't obvious in TypeScript

I have very straightforward 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))

Now I want to make a check:

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

And it returns false.

I tried a few combinations like

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

But, of course, got a compiler error.

The question is how to make quite a basic comparison enum === enum?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The problem is that TypeScript enums are actually "named numeric constants."

From the TypeScript documentation on enums:

Enums allow us to define a set of named numeric constants.

The body of an enum consists of zero or more enum members. Enum members have numeric value (sic) associated with them . . .

You should be using string literal types instead:

type Color = "BLUE" | "RED";


Full Code (View 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
over 4 years ago · Santiago Trujillo Report

0

An alternative (available since TS 2.4) is String enums:

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

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

As there's no reverse mapping for string enums (at least in 2020), one might strongly consider inlining those with const modifier.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!