How to get enum key by value in Typescript?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)