Get an Enum Key by Value in TypeScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get an Enum Key by Value in TypeScript #

To get an enum key by value:

  1. Use the Object.values() method to get an array of the enum's values.
  2. Use the indexOf() method to get the index of the value in the array.
  3. Use the Object.keys() method to get an array of the enum's keys.
  4. Access the array of keys at the specific index.
index.ts
// ✅ For String Enums enum Sizes { Small = 'S', Medium = 'M', Large = 'L', } const indexOfS = Object.values(Sizes).indexOf('S' as unknown as Sizes); const key = Object.keys(Sizes)[indexOfS]; console.log(key); // 👉️ "Small" // ✅ For Numeric Enums enum SizesNumeric { Small, Medium, Large, } console.log(SizesNumeric[0]); // 👉️ "Small" console.log(SizesNumeric[1]); // 👉️ "Medium"

TypeScript enums are real objects and exist at runtime. This is why we are able to pass an enum to the Object.keys and Object.values methods.

The Object.keys() and Object.values() methods return arrays containing the object's keys and values.

index.ts
enum Sizes { Small = 'S', Medium = 'M', Large = 'L', } // 👇️ ['Small', 'Medium', 'Large'] console.log(Object.keys(Sizes)); // 👇️ ['S', 'M', 'L'] console.log(Object.values(Sizes));

We used the indexOf method to get the index of the specific value in the array of values, and then used bracket notation to access the array of keys at the specific index.

If you have to use this approach multiple times, create a reusable function.

index.ts
enum Sizes { Small = 'S', Medium = 'M', Large = 'L', } function getKeyByValue(value: string) { const indexOfS = Object.values(Sizes).indexOf(value as unknown as Sizes); const key = Object.keys(Sizes)[indexOfS]; return key; } console.log(getKeyByValue('S')); // 👉️ Small console.log(getKeyByValue('M')); // 👉️ Medium

If you have to get the key of a numeric enum by a value, use reverse mappings.

index.ts
// ✅ For Numeric Enums enum SizesNumeric { Small, Medium, Large, } console.log(SizesNumeric[0]); // 👉️ "Small" console.log(SizesNumeric[1]); // 👉️ "Medium" console.log(SizesNumeric[2]); // 👉️ "Large"

Unfortunately, you can only use this approach to get tha names of numeric enums.

String enum members don't get a reverse mapping generated at all.

Note that the examples from the article would not work if you use const enums.

Const enums can only use constant enum expressions and are completely removed during compilation.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.