How to check if a given string exists as a value in a string listing in Typescript?

for instance

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 are discussing string enumeration functions.

+5
source share
2 answers

Your listing:

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

This becomes after compilation (at runtime):

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

Therefore, you need to check if there are values in ABC "bb" . For this you can use Object.values โ€‹โ€‹() :

 Object.values(ABC).some(val => val === "bb"); // true Object.values(ABC).some(val => val === "foo"); // false 
+3
source

Your code:

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

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 get true for "A" in ABC and false for "bb" in ABC . Instead, you need to search (for example, a loop) for the values โ€‹โ€‹yourself; A short short liner may be as follows:

 Object.keys(ABC).some(key => ABC[key] === "bb") 

(or you can Object.values over values โ€‹โ€‹directly using Object.values , if supported)

+3
source

Source: https://habr.com/ru/post/1273042/


All Articles