I have a string enum type like:
export enum UserRole {
admin = "admin",
active = "active",
blocked = "blocked"
}
I
The value of an enum
is either a string or number. So, they only way to test, is to test against a string or number.
We can start by creating a User-Defined Type Guard which would look like this:
function isInstance(value: string, type: T): type is T {
return Object.values(type).includes(value)
}
This returns true or false if the value is found in the enum (This doesn't work well on numbers or enums with the same string).
enum Animal {
Cat = 'cat',
Dog = 'dog'
}
enum Plant {
Tree = 'tree',
Flower = 'flower'
}
function isInstance(value: string | number, type: T): type is T {
return Object.values(type).includes(value)
}
console.log(isInstance('dog', Animal)) // True
console.log(isInstance('dog', Plant)) // False