Categories
TypeScript Answers

How to access TypeScript enum by ordinal?

Spread the love

Sometimes, we want to access TypeScript enum by ordinal.

In this article, we’ll look at how to access TypeScript enum by ordinal.

How to access TypeScript enum by ordinal?

To access TypeScript enum by ordinal, we can get the index of the enum entry with Object.keys and array indexOf.

For instance, we write

enum LookingForEnum {
  Romantic = "Romantic",
  Casual = "Casual",
  Friends = "Friends",
  Fun = "Fun",
}

const index: number = Object.keys(LookingForEnum).indexOf("Casual");

to call Object.keys with LookingForEnum to return the keys in the enum.

Then we call indexOf with the key we’re looking for as a string to return the index of the entry.

Therefore, index is 1.

Conclusion

To access TypeScript enum by ordinal, we can get the index of the enum entry with Object.keys and array indexOf.

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 *