Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check does the given string exists as a value in a string enum in Typescript?

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.

like image 349
karina Avatar asked Nov 01 '17 09:11

karina


People also ask

How do you check if the given string is a part of an enum?

toList()). contains(aString); EventNames is the name of the enum while getEvent() is what returns the associated string value of each enum member.

How do you check if a value is present in an enum or not?

Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not. The Enum .

Can an enum have a string value?

Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.

How do I use enum values in TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.


2 Answers

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
like image 158
James Monger Avatar answered Oct 17 '22 00:10

James Monger


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)

like image 29
John Weisz Avatar answered Oct 17 '22 01:10

John Weisz