Function createEnumValueMap

  • Create a map object which contains both the perperty key and value which both map to the resulting value, E[key] => value and E[value] => value.

    Type Parameters

    • E

      Identifies the const enum type being mapped

    Parameters

    • values: {
          [key in string | number | symbol]: E[keyof E]
      }

      The values to populate on the new object

    Returns EnumValueMap<E>

    A new frozen (immutable) object which contains a property for each key and value that returns the value.

    const enum Animal {
    Dog = 0,
    Cat = 1,
    Butterfly = 2,
    Bear = 3
    }
    const animalMap = createEnumValueMap<typeof Animal>({
    Dog: Animal.Dog,
    Cat: Animal.Cat,
    Butterfly: Animal.Butterfly,
    Bear: Animal.Bear
    });
    // You end up with an object that maps everything to the name
    animalMap.Dog === 0; // true
    animalMap[0] === 0; // true
    animalMap["Dog"] === 0; // true
    animalMap.Cat === 1; // true
    animalMap[1] === 1; // true
    animalMap["Cat"] === 1; // true

    // Helper function to always return the "Name" of the type of animal
    function getAnimalValue(type: string | number | Animal) {
    return animalMap[type];
    }