Search code examples
javascripttypescriptenums

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 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?


Solution

  • 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