Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
fasth Avatar asked Mar 25 '17 02:03

fasth


People also ask

How does TypeScript compare to enum?

To compare enums, use dot notation to get the value for a specific enum property and compare it to another value, e.g. if (MyEnum. Small < 2) {} . The values for numeric enums, without provided initial value, are auto-incrementing integers, starting at 0 .

Can you compare string to enum?

To compare a string with an enum, extend from the str class when declaring your enumeration class, e.g. class Color(str, Enum): . You will then be able to compare a string to an enum member using the equality operator == . Copied!

Should you use enums in TypeScript?

Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.


2 Answers

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
like image 92
gyre Avatar answered Sep 17 '22 21:09

gyre


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.

like image 36
raina77ow Avatar answered Sep 19 '22 21:09

raina77ow