'How to return a random enum value in Typescript

I had an entity with 2 different enum properties that I needed to generate with a factory for a test. I wanted to create a reusable function to avoid creating a list of all the enum value for each enum.

private createRandomEntity() : Entity {
  return new Entity({
    status: Status.Success // <--- how to make random
    type: Type.Object // <--- how to make random
  });
}


Solution 1:[1]

After looking online for a while, I found a reusable way to do so by using a function that takes the enum type in parameter

private getRandomEnumValue(enumeration) {
    const values = Object.keys(enumeration);
    const enumKey = values[Math.floor(Math.random() * values.length)];
    return enumeration[enumKey];
}

From my understanding, in typescript, enum are essentially dictionaries, so we can just loop throught them unlike C# or Java.

Source: https://stackblitz.com/edit/typescript-random-enum-value

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MathieuAuclair