I have an enum and a string
enum Keys {
'key1' = 'key1',
'key2' = 'key2'
}
const key = 'key1'
Is there a way to check if key
is part of the enum?
Due to the repetition of the term “key” it’s not clear to me whether you want to check the existence of the property (does Keys.key1 exist?) or the value (is there a property of Keys whose value matches “key1”).
To check for the existence of the property, use Keys[key]
or Keys.hasOwnProperty(key)
. The first is more concise but because it evaluates the value it will return false if the value is falsy e.g.Keys[key] === 0
.
if (Keys[key]) {
// exists with non-falsy value. do stuff.
}
if (Keys.hasOwnProperty(key)) {
// exists. do stuff.
}
To check for the presence of the value, you can use Object.values and Array.includes:
if (Object.values(Keys).includes(key)) {
// do stuff
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments