Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a given string key exists in Enum?

I have an enum defined like this:

export enum someEnum {     None = <any>'',     value1 = <any>'value1',     value2 = <any>'value2',     value3 = <any>'value3'    } 

For example, I want to check "value4" key exists in an enum. I should get false as value4 is not defined on the enum.

I tried if (someEnum['value4']) but got an error:

Element implicitly has an 'any' type because index expression is not of type 'number'.

like image 540
RKS_Code Avatar asked Nov 14 '16 21:11

RKS_Code


People also ask

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 .

How do you check if a string is in an enum Python?

To check if a value exists in an enum in Python: Use a list comprehension to get a list of all of the enum's values. Use the in operator to check if the value is present in the list. The in operator will return True if the value is in the list.

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.


1 Answers

You could use the in operator:

if ('value4' in someEnum) {   // ... } 
like image 144
Ryan Cavanaugh Avatar answered Sep 17 '22 22:09

Ryan Cavanaugh