Ramakant Ramakant - 1 year ago 98
TypeScript Question

How to check if a given string 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" exists in enum. I should get false as value4 is not defined in enum.

I tried
if (someEnum['value4'])
but getting error- Element implicitly has an 'any' type because index expression is not of type 'number'.

Answer Source

You could use the in operator:

if ('value4' in someEnum) {
  // ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download