Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random enum in TypeScript?

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
}
like image 739
Lazar Ljubenović Avatar asked May 28 '17 19:05

Lazar Ljubenović


2 Answers

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.

like image 145
Steven Spungin Avatar answered Sep 18 '22 08:09

Steven Spungin


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];
}
like image 42
Kabir Sarin Avatar answered Sep 20 '22 08:09

Kabir Sarin