Comparing value to enum isn't obvious in TypeScript
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";
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
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.