I have very straightforward code:
enum Color { BLUE, RED }
class Brush {
color: Color
constructor(values) {
this.color = values.color
}
}
let brush = new Brush({ color: "BLUE" })
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.
How to make quite a basic comparison enum === enum
?
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