How to return a random enum value in Typescript

Issue

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

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

Answered By – MathieuAuclair

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.