Issue
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 keybyvaluein that case you have to re write 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:
Another way: Retrieve enum key by value:
let enumKey = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];
console.log(enumKey);
Output:
Test on jsfiddle:
Answered By - Md Farid Uddin Kiron


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.