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
.