7

For example

enum ABC { A = "a", B = "bb", C = "ccc" };

alert("B" in ABC);  // true
alert("bb" in ABC); // false (i wanna true)

Please, keep in mind that we discuss about string enum features.

2
  • 1
    Possible duplicate of Check if value exists in enum in TypeScript Commented Nov 1, 2017 at 10:08
  • 1
    @MedetTleukabiluly -- Unless I'm mistaken, that's not exactly a duplicate, as TypeScript has different compilation logic for numeric and string enums. The solution proposed there wouldn't work here, see compiled output. Commented Nov 1, 2017 at 10:13

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

4

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)

1 Comment

Unfortunately there is no Object.values in typescript :(
1

In ECMAScript 2016 or higher you can also use includes() for this purpose.

Object.values(ABC).includes('bb' as ABC);

See also: This SO answer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.