How to get a random enum in TypeScript?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)