TypeScript Enum Types In-Depth
In TypeScript, an enum type is a convenient data structure used to define a set of named constants. An enum represents an abstract data type that maps a finite set of constants to symbols with descriptive names.
For example, we can use an enum type to represent each day of the week:
enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
In the above example, we define a Weekday enum containing all days in a week. Each constant has a default numeric value that increments starting from zero. Thus, Monday is assigned the value of 0, Tuesday the value of 1, and so on.
We can use this enum type as follows:
let today: Weekday = Weekday.Tuesday;
In the example above, we declare a variable named today with the type Weekday. We assign it the value Weekday.Tuesday, which means that the runtime value of the today variable is 1.
Enums also support specifying values for their constants:
enum Weekday {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
In this example, by setting the value of Monday to 1, TypeScript automatically assigns a value of 2 to Tuesday, and so on.
Enums also support reverse mapping, allowing retrieval of an enum name based on its numeric value:
enum Weekday {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
let dayName = Weekday[2]; // "Tuesday"
In the example above, we retrieve the enum name Tuesday by using the numeric value 2.
In summary, enums are a highly useful data type in TypeScript. They allow for the convenient definition of a finite set of constants and support reverse mapping, resulting in code that is more readable and maintainable.