How to get a random item from an enumeration?
enum Colors {
Red, Green, Blue
}
function getRandomColor(): Color {
// return a random Color (Red, Green, Blue) here
}
After much inspiration from the other solutions, and the keyof
keyword, here is a generic method that returns a typesafe random enum.
function randomEnum<T>(anEnum: T extends object): T[keyof T] {
const enumValues = Object.keys(anEnum)
.map(n => Number.parseInt(n))
.filter(n => !Number.isNaN(n)) as unknown as T[keyof T][]
const randomIndex = Math.floor(Math.random() * enumValues.length)
const randomEnumValue = enumValues[randomIndex]
return randomEnumValue;
}
Use it like this:
interface MyEnum {X, Y, Z}
const myRandomValue = randomEnum(MyEnum)
myRandomValue
will be of type MyEnum
.