typescriptenums

How to get enum key by value in Typescript?


I have an enum like this:

export enum Colors {
    RED = "RED COLOR",
    BLUE = "BLUE COLOR",
    GREEN = "GREEN COLOR"
}

Could you let me know how to get enum key by value please? i.e., I need to pass "BLUE COLOR" and get 'BLUE'.

Colors["BLUE COLOR"] gives error Element implicitly has an 'any' type because expression of type '"BLUE COLOR"' can't be used to index type 'typeof Colors'. Property 'BLUE COLOR' does not exist on type 'typeof Colors'.


Solution

  • If you want to get your enum key by value in that case you have to rewrite your enum in following manners: But same format also might be work in older version as well.

    For Vanilla Js it should be like below:

     enum Colors {
        RED = "RED COLOR",
        BLUE = "BLUE COLOR",
        GREEN = "GREEN COLOR"
    }
    

    For .tsx it should be like below:

     enum Colors {
            RED = "RED COLOR" as any,
            BLUE = "BLUE COLOR" as any,
            GREEN = "GREEN COLOR" as any
        }
    

    For .ts it should be like below:

    enum Colors {
      RED = <any>"RED COLOR",
      BLUE = <any>"BLUE COLOR",
      GREEN = <any>"GREEN COLOR"
    }
    

    Then you can get like this way:

    Retrieve enum key by value:

    let enumKey = Colors["BLUE COLOR"];
        console.log(enumKey);
    

    Output:

    enter image description here

    Another way: Retrieve enum key by value:

    let enumKey = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];
    
    console.log(enumKey);
    

    Output:

    enter image description here

    Test on jsfiddle:

    Coding sample on jsfiddle

    Note: There are new annoucement published on 25th August with TypeScript 4.8. Please be aware of it. You could have a look here.