TypeScript by Example: Enums
Explore TypeScript enumerations for organizing related constants with this sample code. Demonstrates both numeric enums with auto-incrementing values and string enums for readable runtime output, essential patterns for managing configuration and state values.
Code
// Numeric Enum (auto-incrementing)
enum Direction {
Up = 1, // Starts at 1 instead of 0
Down, // 2
Left, // 3
Right // 4
}
// String Enum
enum Status {
Success = "SUCCESS",
Failure = "FAILURE",
Pending = "PENDING"
}
let d: Direction = Direction.Up;
let s: Status = Status.Pending;
console.log(d); // 1
console.log(s); // "PENDING"Explanation
Enums allow you to define a set of named constants. TypeScript provides both numeric and string-based enums. By default, numeric enums are zero-based (0, 1, 2...), but you can manually set the starting value or the value of any member.
String enums allow you to give a meaningful string value to each member. This is useful for debugging because the runtime value is readable, unlike a number. Enums are one of the few TypeScript features that actually generate code (an object) in the compiled JavaScript.
Using enums helps document intent and prevents "magic numbers" or "magic strings" from appearing in your code. It makes the code more maintainable and refactor-friendly.
Code Breakdown
enum Direction creates a numeric enum with auto-incrementing.Up = 1 sets the starting value instead of default 0.enum Status is a string enum requiring explicit values.Success = "SUCCESS" provides readable runtime values.
