TypeScript Enums

Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.


In TypeScript, enums (enumeration) are a data type that allows you to set a group of named constants.

Here's a simple example of enums. You can read the rest of the tutorial to learn more.

Example

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

// Using the enum to set a direction
const currentDirection = Direction.Up;
console.log("Moving in direction:", currentDirection);

// Output: Moving in direction: UP

Here, Direction is enum with possible values "UP", "DOWN", "LEFT" and "RIGHT", and we've used Direction.Up to set the movement direction.


Declaring an Enum

To declare an enum, you use the enum keyword followed by the name of the enum.

enum enumName {
    
    // Set of named members
}

Each member can be a numeric or string value, depending on the type of enum you define.


Types of Enums

There are 2 types of enums.

  • Numeric Enums
  • String Enums

Let's learn about them in detail.


Numeric Enums

In numeric enums, we group related numeric constants under a single name.

By default, the first member of the numeric enum is assigned the value 0, and each subsequent member's value is incremented by one.

enum Level {
  Low,    // Automatically set to 0
  Medium, // Automatically set to 1
  High    // Automatically set to 2
}

console.log(Level.Low);
console.log(Level.Medium);
console.log(Level.High);

Output

0
1
2

Here, we have defined a numeric enum named Level with three members: Low, Medium and High.

Member Value
Low 0
Medium 1
High 2

String Enums

The string enums allow you to assign string literals to the enum members, providing a more meaningful way to handle named constants.

To define a string enum, each member must be initialized with a string value.

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let favoriteColor: Color = Color.Green;
console.log("Favorite Color is:", favoriteColor); 

Output

Favorite Color is: GREEN

Here, Color is an enum that helps manage a set of predefined string values associated with color names.

Notice that we have used Color as a data type to define the favoriteColor variable.

let favoriteColor: Color = Color.Green;

This means, favoriteColor can only be assigned one of the values defined in the Color enum.

Note: Enums ensure that the variables are assigned only from the predefined set of values.


Access Enum values

You can access the enum values in 2 ways:

1. Direct Member Access

2. Index Access

Consider the following example.

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

// Direct member access
console.log("First day of the week:", Day.Sunday);  

// Index access using a variable,
let dayIndex = Day.Monday;
console.log("Second day of the week:", Day[dayIndex]);  

Output

First day of the week: 0
Second day of the week: Monday

Here,

1. Direct Member Access:

Day.Sunday directly accesses the enum member, which is automatically assigned the numeric value 0 as it's the first item.

2. Index Access:

Day[dayIndex] uses an index variable (dayIndex) to access the enum. Here, dayIndex is set to 1, corresponding to Monday, and returns the name "Monday" when used.


Why use Enums?

Enums are used for several reasons, some of which are highlighted below.

1. Improves Readability

Enums improve readability by providing meaningful names to sets of related values. For example,

With Enum

enum Direction {
  North = 0,
  East = 1,
  South = 2,
  West = 3
}

function turn(direction: Direction) {
  console.log("Turning", Direction[direction]);
}

turn(Direction.North);

// Output: Turning North

Here, Direction.North immediately conveys that the direction is north.

Without Enum

function turn(direction: number) {
  const directions = ["North", "East", "South", "West"];
  console.log("Turning", directions[direction]);
}

turn(0);

// Output: Turning North

It's not immediately clear what the number 0 represents unless you look at the array definition.

2. Reduces Errors

Enums prevent assigning invalid values that could lead to runtime errors. For example,

Suppose you need to manage user access levels within an application.

enum AccessLevel {
  Guest,
  User,
  Admin
}

function setAccessLevel(level: AccessLevel) {
  console.log("Your access level:", AccessLevel[level]);
}

setAccessLevel(AccessLevel.Admin);

setAccessLevel(AccessLevel.Super_Admin); // This would cause a compile-time error, as 'Super_Admin' is not a valid AccessLevel

When you try to pass Super_Admin, which is not defined in the AccessLevel enum, it results in a compile-time error.

3. Simplifies Refactoring

Changing the value of an enum member updates it across all usages in the codebase.

enum ServerStatus {
  Offline,
  Online,
  Maintenance
}

function logStatus(status: ServerStatus) {
  console.log("Server is currently", ServerStatus[status]);
}

logStatus(ServerStatus.Online);

Output

Server is currently Online

Suppose you need to add a new status Deprecated to the ServerStaus enum, you can do that:

enum ServerStatus {
  Offline,
  Online,
  Deprecated,  // Newly added
  Maintenance  // Index has shifted, but usage is correct.
}

Adding Deprecated won't disrupt the existing code because references to other statuses like Maintenance will still be correct, even if their positions change.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges