TypeScript Enums
An enum is a way to define a set of named constants, making code more readable than using raw numbers or strings for a fixed list of options. TypeScript supports numeric enums and string enums.
Enums are especially useful for representing things like directions, statuses, or roles, where there is a small, known set of valid values.
enum Direction {
Up,
Down,
Left,
Right
}Numeric enums
By default, enum members are assigned increasing numbers starting at 0, unless you specify your own starting value or explicit values for each member.
String enums
String enums assign a specific string value to each member, which can make debugging easier since the value itself is readable in logs.
enum Direction {
Up,
Down,
Left,
Right,
}
let move: Direction = Direction.Up;
console.log(move);0Up is the first member, so it is assigned the numeric value 0 by default.
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
}
let current: Status = Status.Active;
console.log(current);ACTIVEString enums give each member a specific, readable string value.
Key points
- Enums define a fixed set of named constant values.
- Numeric enums default to 0, 1, 2, ... unless customized.
- String enums assign explicit readable string values.
- Enums make code more descriptive than raw magic numbers or strings.
