Home / Companies / LogRocket / Blog / Post Details
Content Deep Dive

How to iterate over enums in TypeScript (with code examples)

Blog post from LogRocket

Post Details
Company
Date Published
Author
Matteo Di Pirro
Word Count
2,887
Language
-
Hacker News Points
-
Summary

Enums in TypeScript, which model categories like traffic light states or days of the week, have evolved from simple name-to-number mappings to structures that include methods and parameters. The article provides updated insights into iterating over numeric and string enums using methods like `Object.keys()`, `Object.values()`, and `Object.entries()`, as well as comparisons between string and numeric enums. It introduces the `getEnumKeys()` utility function for key extraction and discusses various iteration techniques, including the use of `for` loops and third-party libraries like Lodash, highlighting the importance of understanding enum types for effective iteration. The article emphasizes that the choice of iteration method depends on specific needs, such as preserving enum typing or filtering numeric and string values.