TS Enums
Enums in TypeScript are a way to define a set of named constants. Enums make it easier to manage and use sets of related values in a type-safe manner.
Key Topics
Numeric Enums
Numeric enums assign a numeric value to each member. By default, values start at 0 and increment automatically.
enum Direction {
North,
East,
South,
West
}
console.log(Direction.North); // 0
console.log(Direction.South); // 2
Output
0
2
Explanation: The enum Direction
assigns North = 0
, East = 1
, South = 2
, and West = 3
.
String Enums
String enums assign string values to each member, offering better readability.
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING"
}
console.log(Status.Active); // "ACTIVE"
console.log(Status.Pending); // "PENDING"
Output
ACTIVE
PENDING
Explanation: The enum Status
explicitly maps each member to a string value for better readability and comparison.
Heterogeneous Enums
Heterogeneous enums allow a mix of string and numeric values for members. Use these sparingly for specific use cases.
enum MixedEnum {
Yes = "YES",
No = 0
}
console.log(MixedEnum.Yes); // "YES"
console.log(MixedEnum.No); // 0
Output
YES
0
Explanation: The enum MixedEnum
contains a string member Yes
and a numeric member No
, demonstrating a combination of value types.
Key Takeaways
- Numeric Enums: Use for sequential values starting from 0 by default.
- String Enums: Offer better readability and are ideal for descriptive constants.
- Heterogeneous Enums: Mix value types for specialized use cases but avoid overuse.