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.
>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';
}