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
?
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 .
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!
Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
The problem is that TypeScript enum
s are actually "named numeric constants."
From the TypeScript documentation on enum
s:
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";
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With