Search code examples
javascriptenumskey

Object.freeze() get both worlds


const AnimeState = Object.freeze({
    Idle = 1,
    Walking=2,
    Running=3,
    Attacking = 4,
    Dead = 0,
    Uninitialized: -1
});

this.state = AnimeState.Uninitialized

Trying to get the name of the state, console.log(AnimeState[this.state]) --- this doesn't work however, maybe because of me using the Object.freeze() method here. Is there a way to get both worlds?

Desire: console.log(AnimeState[this.state]) if state === AnimeState.Uninitialized, give me Uninitialized as string.

I followed this link: How to get names of enum entries? and there, they pointed:

enum colors { red, green, blue };

Will be converted essentially to this:

var colors = { red: 0, green: 1, blue: 2,
               [0]: "red", [1]: "green", [2]: "blue" }

Because of this, the following will be true:

colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0

This creates a easy way to get the name of an enumerated as follows:

var color: colors = colors.red;
console.log("The color selected is " + colors[color]);

Solution

  • The problem with the code is that you are try to use the assignment operator (=) instead of the colon (:) to define the property values of the AnimeState object. and also, you are using camelCase instead of PascalCase for the property names.

    You can try this code :

    const AnimeState = Object.freeze({
        IDLE: 1,
        WALKING: 2,
        RUNNING: 3,
        ATTACKING: 4,
        DEAD: 0,
        UNINITIALIZED: -1
    });
    
    let state = AnimeState.UNINITIALIZED;
    console.log(Object.keys(AnimeState).find(key => AnimeState[key] === state)); 
    

    If you that the object will be as enum:

    enum AnimeState {
    UNINITIALIZED = -1,
    DEAD = 0,
    IDLE = 1,
    WALKING = 2,
    RUNNING = 3,
    ATTACKING = 4,
    }
    

    And then assign a value to state like this:

    let state: AnimeState = AnimeState.UNINITIALIZED;