Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validate whether or not string is enum value

I have a TypeScript enum

enum Items {
  One = 1,
  Two,
}

How can I know whether or not string s is a valid string representation of Items? For instance, 'One' is valid but '1' isn’t.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Enums get mapped to objects in JavaScript, so you can do the following:

enum Items {
  One = 1,
  Two,
}

function isEnumValue(s: string): s is keyof typeof Items {
    return s in Items;
}

There is a potential edge case here, because numeric enums also automatically get a reverse mapping. Passing a string representation of an enum value, would also make the above function return true:

console.log(isEnumValue('1')); // true

If needed, this can be addressed by additionally making sure that the key lookup returns a numeric value:

function isEnumValue(s: string): s is keyof typeof Items {
    return s in Items && typeof Items[s as any] === 'number';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading