Get an Enum Key by Value in TypeScript

avatar

Borislav Hadzhiev

Mon Feb 14 20222 min read

banner

Photo by Xan Griffin

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"

Enums in TypeScript 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 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, you can 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 above would not work if you use const enums, because const enums can only use constant enum expressions and are completely removed during compilation.

Use the search field on my Home Page to filter through my more than 1,000 articles.