FewV minutes of Enums in TypeScript

» What are Enums?

  1. Enums is a way to define a set of named values in TypeScript. It allows us to define a set of named constants, where each constant is assigned a unique value.

  2. There are basically two types of enums, those are 1) Numeric based enum and 2) String based enum.

» Numeric enums - Default

  1. Let’s understand Numeric enums with example. Numeric enums are by deafult. We can define an enum for the days of the week like this:
enum DaysOfTheWeek {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}
console.log("Monday has a value of " + DaysOfTheWeek.Monday);
console.log("Tuesday has a value of " + DaysOfTheWeek.Tuesday);
  1. By default in enum, the first value is assigned the number 0, and each subsequent value is assigned an incremented number.

  2. So, in the example above, Monday would have the value 0, Tuesday would have the value 1, and so on.

  3. If we look at this in console:

Console:

Monday has a value of 0

Tuesday has a value of 1
  1. However, we can also explicitly assign values to each enum value:
enum DaysOfTheWeek {
  Monday = 1,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}
console.log("Wednesday is initialized the value " + DaysOfTheWeek.Wednesday);
console.log("Sunday is initialized the value " + DaysOfTheWeek.Sunday);
  1. Here Monday is initialized the value 1, Tuesday is initialized the value 2, and so on.

Console:

Wednesday is initialized the value 3

Sunday is initialized the value 7
  1. We can use enums to make our code more readable and maintainable. However, enums have some limitations as well. Additionally, enums are not well suited for complex or dynamic values.

» String Based Enums

  1. By default, enums in TypeScript are assigned numeric values, starting from 0 and incrementing by 1 for each subsequent value. However, it is also possible to define enums with string values. This is known as a string-based enum.

  2. Here’s an example of a string-based enum:

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}
  1. In this example, each value of the Colors enum is a string. And just like with numeric enums, we can access the values using dot notation:
console.log("My Favourite Color is " + colors.red);

Console:

My Favourite Color is RED
  1. An advantage is that string-based enums are more self-documenting. With string-based enums, the meaning of each value is immediately clear.

  2. In conclusion, enums are a powerful feature in TypeScript that allow us to define a set of named constants. They make our code more readable and maintainable. However, they do have some limitations and are not suitable for all use cases.


I hope this cleared - What are Enums? and its type. Thank You!!😊