How to Create Enum from Array in TypeScript

Updated: January 7, 2024 By: Guest Contributor Post a comment

Introduction

Welcome, esteemed programmers, to the digital pages wherein we divulge the arcane rituals for conjuring TypeScript enums from the common array. Within this grand repository of wisdom, ye shall uncover methods to transmute ordered collections into distinct emblems of constant value.

What be an Enum?

An enum, short for enumeration, is akin to a royal court of values—each a unique noble with a title and a rank, standing in as the constant guardians of your code’s kingdom. Enums in TypeScript serve to elevate mere numbers and strings into clear, semantically significant constants, thereby banishing the foul spectres of confusing numeric codes and repetitive strings.

Creating Enums from Arrays

Lend your eyes and behold the enchantments that transform arrays into enums. Gaze upon the method most foundationary:

enum Days {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

In yonder script, the days of the week have assumed their esteemed positions within an enum—a construct now known to our TypeScript compiler.

From the Array’s Essence

Yet what art we to do, should we possess an array, and wish to erect an enum therefrom? Behold the simplest of incantations:

const daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
enum DaysEnum {
  Sunday = daysArray[0],
  Monday = daysArray[1],
  Tuesday = daysArray[2],
  Wednesday = daysArray[3],
  Thursday = daysArray[4],
  Friday = daysArray[5],
  Saturday = daysArray[6]
}

A trifle laborious, indeed, but worry not, for less strenuous charms lie ahead.

Automagic Transmogrification

Allow me to unfurl a more potent spell—where objects aid our transformation:

const daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
enum DaysEnum {
}
for (let i = 0; i < daysArray.length; i++) {
  DaysEnum[daysArray[i]] = i;
}

This small loop, with each iteration, greets each day and grants it a steady place within our enum. A number it takes, its index by nature, pinning it down in the fabric of types.

Advanced Incantations

But what of a spell that binds both name and number, turning an array into an enum that honors each member’s index—not as its name, but as its value?

const daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let DaysEnum:{[key: string]: number} = {};
daysArray.forEach((day, index) => {
  DaysEnum[day] = index;
});

Lo, the enum now holds tight the order of days, each with its rightful number, whilst their names serve as keys.

Spellbinding Enhancements

Should you wish a bidirectional map, an enum where each day knows its name and number, cast this most advanced spell:

const daysArray = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
function createEnum(arr: T[]): {[K in T]: number} {
  return arr.reduce((acc, curr, index) => {
    acc[curr] = index;
    return acc;
  }, Object.create(null));
}
const DaysEnum = createEnum(daysArray);

The ‘reduce’ method here is a conjurer’s best ally, weaving the array into an enum-like object with both names and numbers aligned, much like the legendary maps of old that showed both landscape and legend.

Final Words

Thou art now vested with powerful know-how to fashion an enum from a mere array, extending thy TypeScript mastery. Employ these spells in crafting software that stands unyielding as the old oak against winds of confusion and change. Go forth, and in thine glorious endeavors, may this newfound knowledge serve thee well.