How to check does the given string exists as a value in a string enum in Typescript?
Your enum:
enum ABC {
A = "a",
B = "bb",
C = "ccc"
};
Becomes this after compilation (at runtime):
var ABC = {
A: "a",
B: "bb",
C: "ccc"
};
Therefore you need to check if any of the values in ABC
is "bb"
. To do this, you can use Object.values():
Object.values(ABC).some(val => val === "bb"); // true
Object.values(ABC).some(val => val === "foo"); // false
Your code:
enum ABC {
A = "a",
B = "bb",
C = "ccc"
};
is compiled to the following JavaScript (see demo):
var ABC;
(function (ABC) {
ABC["A"] = "a";
ABC["B"] = "bb";
ABC["C"] = "ccc";
})(ABC || (ABC = {}));
This is why you are getting true
for "A" in ABC
, and false
for "bb" in ABC
. Instead, you need to look (i.e. loop) for values yourself; a short one liner could be this:
Object.keys(ABC).some(key => ABC[key] === "bb")
(or you could iterate over values directly using Object.values
if supported)