Categories
TypeScript Answers

How to programmatically enumerate an enum type with TypeScript?

Spread the love

Sometimes, we want to programmatically enumerate an enum type with TypeScript.

In this article, we’ll look at how to programmatically enumerate an enum type with TypeScript.

How to programmatically enumerate an enum type with TypeScript?

To programmatically enumerate an enum type with TypeScript, we can use the Object.keys to get the keys and Object.values to get the values.

For instance, we write

const Color = {
  "RED": "Red",
  "ORANGE": "Orange",
  "YELLOW": "Yellow",
  "GREEN": "Green",
  "BLUE": "Blue",
  "INDIGO": "Indigo",
  "VIOLET": "Violet"
}

const colorKeys = Object.keys(Color) as (keyof typeof Color)[];
const colorValues = Object.values(Color);

to call Object.keys with the Color enum to return the keys on the left side in an array.

Then we call Object.values with Color to return an array with the values on the right side in an array.

Conclusion

To programmatically enumerate an enum type with TypeScript, we can use the Object.keys to get the keys and Object.values to get the values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *