DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Understanding Enums in TypeScript: What They Are and How to Use Them

What Are Enums in TypeScript?

Enums, short for "enumerations," are a special feature in TypeScript used for defining sets of named constants. They make your code easier to read and maintain by grouping related values together and giving each one a descriptive name.

Why Use Enums?

  • Prevent magic numbers or strings in your code
  • Make code easier to understand and maintain
  • Catch errors at compile-time

How to Define and Use Enums

Numeric Enums (Default)

enum Direction {
  Up,
  Down,
  Left,
  Right
}

let move: Direction = Direction.Up;
console.log(move); // Output: 0
Enter fullscreen mode Exit fullscreen mode

String Enums

enum Response {
  Yes = "YES",
  No = "NO"
}

function reply(answer: Response) {
  console.log(answer);
}
reply(Response.Yes); // Output: YES
Enter fullscreen mode Exit fullscreen mode

Example Use Case

Suppose you build a navigation menu:

enum Menu {
  Home,
  About,
  Contact
}

function navigate(page: Menu) {
  if (page === Menu.Home) {
    // Navigate to home page
  }
}
Enter fullscreen mode Exit fullscreen mode

Summary:

  • Enums organize sets of related constants
  • Use them for cleaner, safer TypeScript code
  • Both numeric and string enums are available

Tip: Always use enums to avoid hard-coding values when possible.

Top comments (0)