Enum Type in TypeScript

By Hemanta Sundaray on 2023-04-15

In TypeScript, an enum allows you to specify all the possible values that a variable can have. For example:

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

Here, we have an enum named DayOfWeek with seven members representing each day of the week.

Note that, under the hood, TypeScript automatically assigns numeric values to these members starting from 0 and incrementing by 1. So, Sunday is assigned 0, Monday is assigned 1, Tuesday is assigned 2, and so on, up to Saturday which is assigned 6.

Let's log the values of Sunday and Monday and see what we get:

console.log(DayOfWeek.Sunday) // Output: 0
console.log(DayOfWeek.Monday) // Output: 1

As you can see, we obtained 0 and 1 as expected.

The next important point to remember is that, if you want to, you can explicitly set the starting numerical value of an enum. In the example below, we have explicitly assigned the value 1 to the enum member Sunday.

enum DayOfWeek {
  Sunday = 1,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
}

Note that, when you explicitly assign a value to an enum member, TypeScript will automatically increment the subsequent enum member values by 1. So, Monday will be assigned 2, Tuesday will be assigned 3, and so on.

Let's prove this by logging the values of Sunday and Monday to the console:

console.log(DayOfWeek.Sunday) // Output: 1
console.log(DayOfWeek.Monday) // Output: 2

As you can see, we got the expected output.

Next, let's move on to string enums.

String Enums

In the previous section, we studied the `~DayOfWeek~~ enum, which is referred to as a numeric enum because it is based on numeric values automatically assigned by TypeScript.

However, sometimes, you might want to give more meaningful values to enum members instead of just using numbers. This is where string enums come into the picture. With string enums, you can initialize enum members with string values, which can be more descriptive and human-readable.

For example, let's say you're building a web application that involves user authentication. And you want to represent the different roles that users can have, such as "admin", "moderator", and "user". You could use a string enum to define these roles, like this:

enum UserRole {
    admin = "ADMIN"
    moderator = "MODERATOR"
    user = "USER"
}

Join the Newsletter