Enums
Give friendly names to a set of related constant values.
Syntax
enum Direction { Up, Down, Left, Right }An enum defines a named group of constants. Instead of remembering raw numbers or strings, you use readable names.
Numeric enums
By default enum members are numbered starting at 0. You can access members by name for clear, self-documenting code.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A status field in an order system uses a numeric enum so each state has a readable constant instead of a magic number.
- A direction enum in a game engine maps movement keys to named constants for clearer switch-case logic.
- A priority enum in a task manager assigns integer values to Low, Medium, and High for sorting purposes.
More examples
Numeric enum declaration
Declares a numeric enum whose members auto-increment from 0, and reverse-maps from the value back to the name.
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
function move(dir: Direction): void {
console.log('Moving:', Direction[dir]);
}
move(Direction.Up);Enum with custom start value
Assigns explicit numeric values matching real HTTP status codes so enum members carry meaningful values.
enum HttpStatus {
OK = 200,
Created = 201,
BadRequest = 400,
Unauthorized = 401,
NotFound = 404,
}
function isSuccess(status: HttpStatus): boolean {
return status >= 200 && status < 300;
}Using enum in a switch
Uses an enum in a switch statement for exhaustive case handling with named constants instead of raw numbers.
enum Priority { Low = 1, Medium = 2, High = 3 }
function label(p: Priority): string {
switch (p) {
case Priority.Low: return 'low';
case Priority.Medium: return 'medium';
case Priority.High: return 'high';
}
}
Discussion