Iterating over a TypeScript Enum

Published June 10, 2021

Here are ways that you can turn a TypeScript enum into an array that you can iterate over. Let's say we have the following enum called Categories that has different names for its keys and values.

enum Categories {
  AllCategories = 'All',
  ActionAdventure = 'Action/Adventure',  
  Comedy = 'Comedy',
}

Keys

We can get the enum's keys by doing the following.

const categoryKeys: Array<string> = Object.keys(Categories);

console.log(categoryKeys);
// ["AllCategories", "ActionAdventure", "Comedy"]  

We can iterate over the enum's keys to get it's values.

const values: Array<Categories> = categoryKeys.map(categoryKey => Categories[categoryKey]);
// with 'noImplicitAny' disabled in tsconfig.json

console.log(values);
// ["All", "Action/Adventure", "Comedy"] 

Without noImplicitAny being disabled in tsconfig.json, the Categories[key] reference will throw an error because we are trying to access a Categories property using a string key. TypeScript warns that since key is a string, it can be equal to anything, not just the key names in Categories.

We can fix this error by defining a new key variable with keyof typeof Categories and casting categoryKey to the same type using the as keyword. The possible values of key will now be limited to only the names of the Categories keys. TypeScript will be fine with this adjustment that we've made.

const values: Array<Categories> = categoryKeys.map(categoryKey => {
  const key: keyof typeof Categories = categoryKey as keyof typeof Categories;
  return Categories[key];
});

console.log(values);
// ["All", "Action/Adventure", "Comedy"] 

Values

We can also get the enum's values by doing the following.

const values: Array<Categories> = Object.values(Categories);

console.log(values);
// ["All", "Action/Adventure", "Comedy"]