How to Use Enums in TypeScript Step-by-Step

Enums in TypeScript are a way to define a set of named constants that can be used to represent a collection of related values. They make code more readable and maintainable by giving friendly names to these values. This guide will walk you through using enums in TypeScript step-by-step, covering their types, benefits, and practical examples.

What is an Enum?

An enum (short for "enumeration") is a special data type in TypeScript that allows you to define a set of named constants. These named constants can represent numeric or string values, making your code more descriptive and less error-prone.

Types of Enums in TypeScript

There are three types of enums in TypeScript:

  • Numeric Enums
  • String Enums
  • Heterogeneous Enums

Numeric Enums

Numeric enums are the default in TypeScript. They are a set of named values that are automatically assigned numeric values starting from 0, or from a custom starting value if specified.

Basic Numeric Enum Example

Below is a simple example of a numeric enum:

enum Direction {
  Up,
  Down,
  Left,
  Right
}

let move: Direction = Direction.Up;
console.log(move); // Output: 0

In this example, the Direction enum has four members: Up, Down, Left, and Right. By default, Up is assigned the value 0, Down is 1, and so on. You can also specify custom numeric values for the members.

Numeric Enum with Custom Values

You can assign custom values to enum members:

enum Status {
  New = 1,
  InProgress,
  Done = 5,
  Cancelled
}

console.log(Status.New); // Output: 1
console.log(Status.InProgress); // Output: 2
console.log(Status.Done); // Output: 5
console.log(Status.Cancelled); // Output: 6

In this example, New is set to 1, InProgress is automatically set to 2, Done is set to 5, and Cancelled is automatically set to 6.

String Enums

String enums are another type of enum where each member is initialized with a string literal, making them more readable and easier to debug.

Basic String Enum Example

Below is an example of a string enum:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

let move: Direction = Direction.Left;
console.log(move); // Output: "LEFT"

In this example, each enum member is initialized with a string value. Unlike numeric enums, string enums do not have auto-incremented values.

Heterogeneous Enums

Heterogeneous enums are enums that contain both string and numeric members. While it is possible to define them, it is generally not recommended as it can lead to confusion and errors in code.

Heterogeneous Enum Example

Here is an example of a heterogeneous enum:

enum MixedEnum {
  Yes = "YES",
  No = 0,
  Maybe = 1
}

console.log(MixedEnum.Yes); // Output: "YES"
console.log(MixedEnum.No); // Output: 0

In this example, MixedEnum contains both string and numeric values. Use such enums cautiously as they may cause confusion.

Enum Use Cases

Enums are helpful in a variety of scenarios:

  • Representing a set of related constants like directions (Up, Down, Left, Right).
  • Defining states in a state machine (New, InProgress, Done, Cancelled).
  • Using them in switch-case statements for better readability.

Enum in a Switch-Case Example

Using enums in a switch-case statement improves code readability and makes it easier to manage states.

enum Status {
  New,
  InProgress,
  Done,
  Cancelled
}

function getStatusMessage(status: Status): string {
  switch (status) {
    case Status.New:
      return "The task is new.";
    case Status.InProgress:
      return "The task is in progress.";
    case Status.Done:
      return "The task is completed.";
    case Status.Cancelled:
      return "The task is cancelled.";
    default:
      return "Unknown status.";
  }
}

console.log(getStatusMessage(Status.InProgress)); // Output: "The task is in progress."

In this example, the switch-case statement is more readable and less prone to errors, thanks to using enums.

Conclusion

Enums in TypeScript provide a powerful way to define a set of named constants, improving code readability and type safety. By using numeric, string, or even heterogeneous enums, you can better manage and organize your code. With this step-by-step guide, you should now be comfortable using enums in TypeScript to make your code cleaner and more maintainable.