LogRocket Blog

How to iterate over enums in TypeScript

thumbnail
  • In TypeScript, enums can be iterated over using various methods such as inbuilt object methods, for loops, and Lodash.
  • The inbuilt object methods, such as "Object.keys" and "Object.values", can be used to list the keys and values of an enum. To filter out numeric keys or values, a filter can be applied.
  • For loops can also be used to iterate over the keys and then reverse map them to get the enum values. However, this method may not work for enums backed by string values.
  • Lodash's "forEach" method can be used to iterate over an enum by passing a function that handles each key-value pair. This method preserves the typing of the enum values.
  • The chosen method for iterating over enums depends on the specific requirements and whether the enum typing needs to be preserved.