Function createEnumKeyMap

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

    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 EnumNameMap<E>

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

    Example

    const enum Animal {
    Dog = 0,
    Cat = 1,
    Butterfly = 2,
    Bear = 3
    }
    const animalMap = createEnumKeyMap<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 === "Dog"; // true
    animalMap[0] === "Dog"; // true
    animalMap["Dog"] === "Dog"; // true
    animalMap.Cat === "Cat"; // true
    animalMap[1] === "Cat"; // true
    animalMap["Cat"] === "Cat"; // true
    // Helper function to always return the "Name" of the type of animal
    function getAnimalType(type: string | number | Animal) {
    return animalMap[type];
    }