TypeScript | Convert Enums to Arrays

Enums are a special type not found in regular JavaScript allowing us to define constants to run logic based on different cases. Sometimes we need to access a list of defined constants in an iterative way, such as generating a list of dropdown values or generate custom objects off of the enum key values.

Enums are objects when code is compiled into JavaScript. Given the following Enum:

enum AnimalType {
  Invertebrates = 'Invertebrates',
  Reptiles = 'Reptiles',
  Mammals = 'Mammals',
  Fish = 'Fish',
  Birds = 'Birds',
  Amphibians = 'Amphibians',
}

Once this code is converted to JavaScript, we will have the following outcome:

var AnimalType;
(function (AnimalType) {
    AnimalType["Invertebrates"] = "Invertebrates";
    AnimalType["Reptiles"] = "Reptiles";
    AnimalType["Mammals"] = "Mammals";
    AnimalType["Fish"] = "Fish";
    AnimalType["Birds"] = "Birds";
    AnimalType["Amphibians"] = "Amphibians";
})(AnimalType || (AnimalType = {}));

At first, it looks like an odd function. However, it is a self-invoking functioning that populates an object with multiple property keys with their respective value.

Converting Enum to Array

Since enums are objects, we can use similar iterative solutions to access all values and put them in an array, such as Object.keys() function mixed with a map.

const animalTypes = Object.keys(AnimalType).map((key) => ({ key , value: AnimalType[key] }));

Another option is to use a for in and iterate over each enum key to access their respective value.

const animalTypes = [];
for (const key in AnimalType) {
  if (Object.prototype.hasOwnProperty.call(AnimalType, key)) {
    animalTypes.push({ key , value: AnimalType[key] }) ;
  }
}

As a result, we will get an array with the following values:

// [
//   { key: 'Invertebrates', value: 'Invertebrates' },
//   { key: 'Reptiles', value: 'Reptiles' },
//   { key: 'Mammals', value: 'Mammals' },
//   { key: 'Fish', value: 'Fish' },
//   { key: 'Birds', value: 'Birds' },
//   { key: 'Amphibians', value: 'Amphibians' }
// ]

Beware of TypeScript Configuration

It is a common practice to have a tsconfig.json file at the root of the project to set the compiler options required to compile the project. Based on the configuration settings, it could create problems with the previous examples to convert an enum to an array. For example, if the tsconfig.json file has "noImplicitAny": true as part of the compilerOptions, it will generate the following error:

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof AnimalType'

ES8 or ES2017

You can define a target as part of the compilerOptions. Using ES6 is generally a common practice as most browsers nowadays support it. However, in case your project has set the target to ES8 or ES2017 (it is the same target for those who don’t know), you could use another function provided to objects, which is Object.entries().

console.log(
  Object.entries(AnimalType)
);

// Result
// [
//   [ 'Invertebrates', 'Invertebrates' ],
//   [ 'Reptiles', 'Reptiles' ],
//   [ 'Mammals', 'Mammals' ],
//   [ 'Fish', 'Fish' ],
//   [ 'Birds', 'Birds' ],
//   [ 'Amphibians', 'Amphibians' ]
// ]

Although the structure of each item of the array is different, you can use it with other array functions such as map(), or filter() to make the necessary changes to generate the array items you need.

More TypeScript Tips!

There is a list of TypeScript tips you might be interested in checking out

Did you like this TypeScript tip?

Share your thoughts by replying on Twitter of Become A Better Programmer or to personal my Twitter account.