FewV minutes of Enums in TypeScript
» What are Enums?
-
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.
-
There are basically two types of enums, those are 1) Numeric based enum and 2) String based enum.
» Numeric enums - Default
- 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);
-
By default in enum, the first value is assigned the number 0, and each subsequent value is assigned an incremented number.
-
So, in the example above, Monday would have the value 0, Tuesday would have the value 1, and so on.
-
If we look at this in console:
Console:
Monday has a value of 0
Tuesday has a value of 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);
- 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
- 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
-
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.
-
Here’s an example of a string-based enum:
enum Colors {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
- 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
-
An advantage is that string-based enums are more self-documenting. With string-based enums, the meaning of each value is immediately clear.
-
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!!😊