Back to Course

Learn TypeScript

0% Complete
0/0 Steps
Lesson 19 of 25
In Progress

Enums in Typescript

Enums, short for enumerations, are a feature in Typescript that allow you to define a set of named constants. Enums are a powerful tool that can be used to improve the readability and maintainability of your code. In this article, we will explore the basics of enums in Typescript and learn how to use them effectively in our projects.

What are Enums?

Enums are a way to define a set of named constants in Typescript. They are a kind of data type that consists of a set of named values, called members. Each member has a name and a value associated with it. The value of an enum member can be a string or a number, and it is usually an integer.

Here’s an example of an enum in Typescript:

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

In this example, we have defined an enum called Days with seven members, each representing a day of the week. By default, the value of each member is its position in the enum, starting at 0 for the first member. So, in this example, Sunday has a value of 0, Monday has a value of 1, and so on.

You can also specify the value of an enum member explicitly, like this:

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

In this case, Sunday has a value of 1, Monday has a value of 2, and so on. You can also use strings as the value of an enum member, like this:

enum Days {
  Sunday = "SUN",
  Monday = "MON",
  Tuesday = "TUE",
  Wednesday = "WED",
  Thursday = "THU",
  Friday = "FRI",
  Saturday = "SAT"
}

In this example, each member has a string value representing the abbreviation of the day of the week.

Using Enums:

Once you have defined an enum, you can use its members in your code just like any other variable. For example, you can use an enum member as a value for a function parameter or as the return type of a function.

function getDayName(day: Days): string {
  switch (day) {
    case Days.Sunday:
      return "Sunday";
    case Days.Monday:
      return "Monday";
    // ...
  }
}

In this example, we have defined a function called getDayName that takes a Days enum member as a parameter and returns a string with the name of the day of the week.

You can also use the enum keyword to get the value of an enum member. For example:

console.log(Days.Sunday); // outputs 0 
console.log(Days[0]); // outputs "Sunday"

In the first line, we are logging the value of the Sunday member, which is 0. In the second line, we are logging the name of the member with a value of 0, which is "Sunday".

Advantages of Enums:

Enums, or enumerations, are a powerful feature in Typescript that allow developers to define a set of named constants. This can be especially useful when working with a fixed set of values that are meant to be represented as a group, such as the days of the week or the suits in a deck of cards.

One of the main advantages of using enums is that they provide a clear and concise way to represent a group of related values. This can help to improve the readability and maintainability of your code, as it clearly defines the values that are expected and allows you to easily reference them throughout your codebase.

Another advantage of enums is that they allow you to assign a specific type to each member, which can be especially useful when working with large codebases where it may not always be clear what type a particular value should be. By using enums, you can ensure that all members are of the same type and that the type is clearly defined and easy to understand.

Finally, enums can also help to improve the performance of your code by allowing the Typescript compiler to optimize the code for the specific values that are being used. This can result in faster and more efficient code, which can be especially important when working with large and complex projects.

Overall, enums are a valuable tool for developers working with Typescript, and can help to improve the readability, maintainability, and performance of your code.

Advanced Features of Enums:

Enums also have some advanced features that you can use to customize their behavior and make them even more useful.

One of these features is the ability to define computed members in an enum. Computed members are members whose value is computed at runtime based on an expression. For example:

enum Days {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Total = Sunday + Saturday + 1
}

In this example, the Total member is a computed member that is calculated at runtime based on the values of the Sunday and Saturday members. The result of this expression is 7, which is the total number of days in a week.

Another advanced feature of enums is the ability to define constant members. Constant members are members whose value cannot be changed after the enum is defined. For example:

enum Days {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Total = Sunday + Saturday + 1,
  readonly Weekend = Sunday + Saturday
}

In this example, the Weekend member is a constant member whose value is the sum of the values of the Sunday and Saturday members. This value cannot be changed after the enum is defined.

Conclusion:

Enums are a useful feature in Typescript that can help you improve the readability and maintainability of your code. They allow you to define a set of named constants and use them in your code just like any other variable. With advanced features like computed members and constant members, enums can be customized to fit your specific needs.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Write a function called getDayNumber that takes a day name (a string) as a parameter and returns the corresponding day number from the Days enum. If the day name is not a valid member of the enum, the function should return -1.

function getDayNumber(dayName: string): number {
  switch (dayName) {
    case "Sunday":
      return Days.Sunday;
    case "Monday":
      return Days.Monday;
    case "Tuesday":
      return Days.Tuesday;
    case "Wednesday":
      return Days.Wednesday;
    case "Thursday":
      return Days.Thursday;
    case "Friday":
      return Days.Friday;
    case "Saturday":
      return Days.Saturday;
    default:
      return -1;
  }
}

Write a function called isWeekend that takes a day number (a number) as a parameter and returns a boolean indicating whether the day is a weekend day or not. You should use the Days enum to determine the weekend days.

function isWeekend(dayNumber: number): boolean {
  return dayNumber === Days.Sunday || dayNumber === Days.Saturday;
}

Write a function called getDayNameFromNumber that takes a day number (a number) as a parameter and returns the corresponding day name from the Days enum. If the day number is not a valid member of the enum, the function should return null.

function getDayNameFromNumber(dayNumber: number): string | null {
  switch (dayNumber) {
    case Days.Sunday:
      return "Sunday";
    case Days.Monday:
      return "Monday";
    case Days.Tuesday:
      return "Tuesday";
    case Days.Wednesday:
      return "Wednesday";
    case Days.Thursday:
      return "Thursday";
    case Days.Friday:
      return "Friday";
    case Days.Saturday:
      return "Saturday";
    default:
      return null;
  }
}

Write a function called getNextWeekday that takes a day name (a string) as a parameter and returns the name of the next weekday. For example, if the input is “Monday”, the output should be “Tuesday”. If the input is “Friday”, the output should be “Monday”. You should use the Days enum to determine the next weekday.

function getPreviousWeekday(dayName: string): string {
  const dayNumber = getDayNumber(dayName);
  if (dayNumber === Days.Monday) {
    return "Friday";
  } else {
    return getDayNameFromNumber(dayNumber - 1);
  }
}

Write a function called isWeekday that takes a day name (a string) as a parameter and returns a boolean indicating whether the day is a weekday or not. You should use the Days enum to determine the weekdays.

function isWeekday(dayName: string): boolean {
  const dayNumber = getDayNumber(dayName);
  return dayNumber > Days.Sunday && dayNumber < Days.Saturday;
}