How to get a random enum in TypeScript?

Most of the above answers are returning the enum keys, but don't we really care about the enum values?

If you are using lodash, this is actually as simple as:

_.sample(Object.values(myEnum)) as MyEnum

The casting is unfortunately necessary as this returns a type of any. :(

If you're not using lodash, or you want this as its own function, we can still get a type-safe random enum by modifying @Steven Spungin's answer to look like:

function randomEnum<T>(anEnum: T): T[keyof T] {
  const enumValues = (Object.values(anEnum) as unknown) as T[keyof T][];
  const randomIndex = Math.floor(Math.random() * enumValues.length);
  return enumValues[randomIndex];
}

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): 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.


How about this, using Object.values from es2017 (not supported by IE and support in other browsers is more recent):

function randEnumValue<T>(enumObj: T): T[keyof T] {
  const enumValues = Object.values(enumObj);
  const index = Math.floor(Math.random() * enumValues.length);
  
  return enumValues[index];
}