Loop over a TypeScript Enum

Find out how you can iterate or loop over a TypeScript Enum of string values.
June 10, 2021TypeScript
3 min read

Iterating over the string values of a TypeScript Enum can be easily accomplished by converting that Enum into an array. Let's say we have the following Enum called Categories that contains different names for its keys and values.

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

Get the keys

We can get the Enum's keys by using the Object.keys() JavaScript method.

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

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

This will give us the Enum's key values as an array of strings that we can iterate over.

Get the values with the keys

We can iterate over the Enum's keys that we got above in order to get the Enum's values.

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

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

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

If the noImplicitAny rule is not disabled in tsconfig.json, the Categories[categoryKey] 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. We won't have to make adjustments to the noImplicitAny TypeScript rule with this approach.

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"] 

This will give us an array of strings that we can iterate over.

Get the values

We can also get the Enum's values by using the Object.values() JavaScript method. This will give us an array of strings that we can iterate over.

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

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

Conclusion

We can use the Object.values() JavaScript method to iterate over the string values of a TypeScript Enum. We can also use the Object.keys() JavaScript method and then iterate over the Enum's keys to get its values.

For more help with TypeScript Enums, I have a blog post on how to Get the keys of a numeric TypeScript Enum.

New
Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.