How to Access the Keys and Values of an Enum (String and Numeric) in TypeScript

TypeScript enums are real objects that exist at runtime. You can use the “Object.keys()” or “Object.values()” methods to access the keys or values.

How to Access All the Keys of a String Enum

To access all the enum keys in TypeScript, you can use the “Object.keys()” method.

enum Cars {
  BMW = "B",
  Cadillac = "C",
  TataMotors = "T",
  Ford = "F",
}

const keys = Object.keys(Cars);

console.log(keys);

Output

How to Access All the Keys of an Enum

How to Access All the Values of a String Enum

To access the values of an Enum, you can use the “Object.values()” method.

enum Cars {
  BMW = "B",
  Cadillac = "C",
  TataMotors = "T",
  Ford = "F",
}

const keys = Object.values(Cars);

console.log(keys);

Output

How to Access All the Values of an Enum

How to Access a Specific Value in an Enum using the Key

You can access the value of an enum key when you have the key as a string at runtime.

Here are the steps to do that:

  1. Use Object.keys() to get an array of the enum’s keys.
  2. Use indexOf() to find the index of the desired key.
  3. Use the index to access the corresponding value.
enum Colors {
  RED = "Red Color",
  BLUE = "Blue Color",
  GREEN = "Green Color"
}

// Let's say you have the key as a string at runtime:
const keyName = "RED";

// 1. Get the keys of the enum
const enumKeys = Object.keys(Colors);

// 2. Find the index of the desired key
const index = enumKeys.indexOf(keyName);

// 3. Access the corresponding value using the index
const value = Colors[enumKeys[index]];

console.log(value);

Output

How to Access a Specific Value in an Enum using the Key

How to Access the Values in a Numeric Enum

You can directly access the value of Enum using either the index of the value or the numeric key assigned to the value.

enum Days {
 Sunday,
 Monday,
 Tuesday,
 Wednesday,
 Thursday,
 Friday,
 Saturday
}

console.log(Days[0]);
console.log(Days[1]);
console.log(Days[5]);
console.log(Days[6]);

Output

How to Access the Values in a Numeric Enum

How to Access All the Keys or Values of a Numeric Enum

You can use the “Object.values()” or “Object.keys()” method will return both the keys and values in a combined array.

enum Days {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}
const values = Object.values(Days);
console.log(values);

const keys = Object.keys(Days);
console.log(keys);

Output

How to Access All the Keys or Values of a Numeric Enum

I hope this will help you!

Related posts

TypeScript String to Enum

TypeScript Enum to Array

TypeScript String to Number

TypeScript String to Boolean

Leave a Comment