← Back to TypeScript Course | Chapter 19: Enums Deep Dive | Lesson 1 of 6

Numeric Enums

Numeric enums assign numeric values to named members. They are useful when an application needs readable names backed by numbers.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.