Enumerations in TypeScript: Working with Enum Names and Values

In TypeScript, enumerations (enums) allow you to define a set of named values. Enums are useful when you need to define a set of distinct values that have a specific meaning in your code. In this tutorial, we will explore how to work with enum names and values in TypeScript.

Defining an Enum

An enum is defined using the enum keyword followed by the name of the enum and a set of named values. For example:

enum Color {
  Red,
  Green,
  Blue
}

In this example, we define an enum called Color with three named values: Red, Green, and Blue.

Enum Values

By default, enum values are numeric and start from 0. You can access the value of an enum member using its name:

console.log(Color.Red); // outputs 0
console.log(Color.Green); // outputs 1
console.log(Color.Blue); // outputs 2

You can also assign a specific value to an enum member:

enum Color {
  Red = 10,
  Green,
  Blue
}

In this example, Red is assigned the value 10, and Green and Blue are assigned the next two values (11 and 12).

Enum Names

To get the name of an enum member, you can use the enum member’s value as a key to access its corresponding string value:

console.log(Color[Color.Red]); // outputs "Red"
console.log(Color[Color.Green]); // outputs "Green"
console.log(Color[Color.Blue]); // outputs "Blue"

This works because TypeScript creates a reverse mapping for numeric enum values, where the value is used as a key to access its corresponding string value.

Iterating Over Enum Members

To iterate over enum members and get their names, you can use a for...in loop:

for (const member in Color) {
  console.log(member); // outputs "Red", "Green", "Blue"
}

Note that this will also include the numeric values as strings (e.g., "0", "1", "2"). To filter out these values, you can check if the value is a number:

for (const member in Color) {
  if (isNaN(Number(member))) {
    console.log(member); // outputs "Red", "Green", "Blue"
  }
}

Alternatively, you can use Object.keys() to get an array of enum member names and then filter out the numeric values:

const enumNames = Object.keys(Color).filter(key => isNaN(Number(key)));
console.log(enumNames); // outputs ["Red", "Green", "Blue"]

Best Practices

When working with enums, it’s a good practice to use meaningful names for your enum members and to avoid using numeric values directly in your code. Instead, use the enum member names to make your code more readable and maintainable.

In summary, this tutorial has covered the basics of working with enum names and values in TypeScript, including defining an enum, accessing enum values and names, iterating over enum members, and best practices for using enums effectively.

Leave a Reply

Your email address will not be published. Required fields are marked *