2 min read

TypeScript Enums

Enums (Enumerations) allow you to define a set of named constants. Using enums can make it easier to document intent or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

1. Numeric Enums

By default, enums are number-based. They start at zero and increment by 1 for each member.

enum Direction {
  Up,    // 0
  Down,  // 1
  Left,  // 2
  Right  // 3
}

let move: Direction = Direction.Up;

You can also initialize the first member, and the rest will auto-increment from there.

enum Direction {
  Up = 1,
  Down, // 2
  Left, // 3
  Right // 4
}

Reverse Mapping

Numeric enums support reverse mapping. You can access the name of the enum member using its value.

console.log(Direction[1]); // Output: "Up"

2. String Enums

String enums allow you to give a meaningful string value to each member. They do not have auto-incrementing behavior, but they are easier to debug because the value is readable at runtime.

enum Status {
  Success = "SUCCESS",
  Failure = "FAILURE",
  Pending = "PENDING"
}

if (response.status === Status.Success) {
  console.log("Operation worked!");
}

3. Enums vs Union Types

A common alternative to Enums is using Union Types with string literals.

// Enum approach
enum LogLevel {
  Error,
  Warning,
  Info
}

// Union Type approach
type LogLevelType = "Error" | "Warning" | "Info";

When to use which?

  • Use Enums if you need to iterate over the values or need a mapping between keys and values (like a dropdown list).
  • Use Union Types for simple string constants, as they are lighter weight and compile away completely in JavaScript.

programming/javascript/typescript/typescript