Numeric Enums
In this page:
Basic Numeric Enum
A numeric enum automatically assigns increasing numeric values starting from 0 when no initializer is given, so the first member is 0, the second is 1, and so on unless you override it.
Example: Basic Numeric Enum
enum Direction {
Up,
Down,
Left,
Right,
}
console.log(Direction.Up, Direction.Right);
Custom Numeric Values
Enum members can start at a chosen number, and every member after it continues incrementing from there — useful when the underlying numeric values need to match an external system's own numbering.
Example: Custom Numeric Values
enum StatusCode {
Ok = 200,
NotFound = 404,
ServerError = 500,
}
console.log(StatusCode.NotFound);
Using Numeric Enums in Functions
Functions can accept an enum value as a parameter type to restrict callers to one of the named numeric choices, instead of accepting a bare number that could be any arbitrary integer.
Example: Using Numeric Enums in Functions
enum Direction { Up, Down, Left, Right }
function move(direction: Direction) {
return `Moving in direction ${direction}`;
}
console.log(move(Direction.Left));
Numeric Enum Comparisons
Numeric enum values can be compared directly with named members when business logic genuinely depends on the specific number assigned, though this couples the code to those exact values.
Example: Numeric Enum Comparisons
enum Priority { Low = 1, Medium, High }
const level = Priority.Medium;
console.log(level === Priority.Medium, level > Priority.Low);
When to Use Numeric Enums
Numeric enums fit best when named states need stable numeric values, particularly when those numbers have a meaningful external representation — like matching status codes from a legacy system or database.
Example: When to Use Numeric Enums
enum HttpStatus {
Ok = 200,
Created = 201,
NotFound = 404,
}
console.log(HttpStatus.Created);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: