TypeScript Enums
Learn how to define named constants using enums, work with numeric and string enums, assign custom values, and use enum members in applications.
1. What is an Enum?
Enum stands for enumeration. In TypeScript, an enum defines a set of named members that represent related values.
For example, an application might have order statuses such as Pending, Shipped and Delivered. An enum lets us refer to these values by name instead of repeating unexplained numeric values or strings throughout the code.
Basic Syntax
enum Direction {
North,
South,
East,
West
}
console.log(Direction.North);
console.log(Direction.South);
console.log(Direction.East);
console.log(Direction.West);
Expected Output
0
1
2
3
By default, numeric enum members start at 0 and increase by 1. Therefore, North is 0, South is 1, East is 2 and West is 3.
2. Enum Workflow Diagram
Understand how an enum defines named values and how those values are accessed in a TypeScript application.
Declare Enum
Group related members using the enum keyword.
Define Members
Choose member names and optional values.
Access Member
Use the enum name and member name.
Use Value
Use the selected value in conditions and application logic.
Direction.North or OrderStatus.Pending.
3. Numeric Enums
Numeric enums assign numbers to their members. When no starting value is provided, the first member is 0 and each following member increases by 1.
Example
enum PaymentStatus {
Pending,
Completed,
Failed
}
const status: PaymentStatus = PaymentStatus.Completed;
console.log(PaymentStatus.Pending);
console.log(PaymentStatus.Completed);
console.log(PaymentStatus.Failed);
console.log(status);
Expected Output
0
1
2
1
Numeric Enum Values
| Enum Member | Numeric Value | Meaning |
|---|---|---|
Pending |
0 | Payment is waiting to be processed. |
Completed |
1 | Payment has completed. |
Failed |
2 | Payment was unsuccessful. |
4. Enums with Custom Numeric Values
You can explicitly assign numbers to enum members. If a numeric member is assigned a value, the following automatically initialized numeric member uses the previous value plus one.
Example
enum HttpStatus {
OK = 200,
Created = 201,
BadRequest = 400,
NotFound = 404
}
console.log(HttpStatus.OK);
console.log(HttpStatus.Created);
console.log(HttpStatus.BadRequest);
console.log(HttpStatus.NotFound);
Expected Output
200
201
400
404
Custom numeric values are helpful when your application works with predefined numeric codes, such as status codes or internal identifiers.
5. String Enums
String enums assign a string value explicitly to every member. They are useful when named values need to be readable in logs, API data or application workflows.
Example
enum UserRole {
Admin = "ADMIN",
Trainer = "TRAINER",
Student = "STUDENT"
}
const role: UserRole = UserRole.Trainer;
console.log(UserRole.Admin);
console.log(UserRole.Trainer);
console.log(UserRole.Student);
console.log(role);
Expected Output
ADMIN
TRAINER
STUDENT
TRAINER
String Enum Diagram
Admin
"ADMIN"
Trainer
"TRAINER"
Student
"STUDENT"
6. Using Enums with Conditions
Enums make conditions easier to read because the code uses meaningful member names instead of unexplained numeric or string values.
Example: Order Status
enum OrderStatus {
Pending,
Shipped,
Delivered
}
function displayOrderStatus(status: OrderStatus): void {
if (status === OrderStatus.Pending) {
console.log("Order is waiting for dispatch");
} else if (status === OrderStatus.Shipped) {
console.log("Order is on the way");
} else if (status === OrderStatus.Delivered) {
console.log("Order has been delivered");
}
}
displayOrderStatus(OrderStatus.Shipped);
Expected Output
Order is on the way
The function accepts a value of type OrderStatus
and runs the appropriate branch based on the selected member.
7. Enums with Switch Statements
A switch statement is useful when different enum members require different actions. Each case clearly identifies the value being handled.
Example
enum TrafficLight {
Red,
Yellow,
Green
}
function trafficAction(light: TrafficLight): void {
switch (light) {
case TrafficLight.Red:
console.log("Stop");
break;
case TrafficLight.Yellow:
console.log("Get Ready");
break;
case TrafficLight.Green:
console.log("Go");
break;
}
}
trafficAction(TrafficLight.Green);
Expected Output
Go
Traffic Light Workflow
TrafficLight
Select Red, Yellow or Green.
Switch
Compares the selected enum member with each case.
Action
Executes Stop, Get Ready or Go.
8. Reverse Mapping in Numeric Enums
Numeric enums provide reverse mapping in the generated JavaScript. That means you can look up a member by its numeric value as well as look up the numeric value by its member name.
Example
enum Status {
Pending,
Completed,
Failed
}
console.log(Status.Pending);
console.log(Status[1]);
Expected Output
0
Completed
Status.Pending returns the numeric value 0.
Status[1] returns the member name "Completed".
This reverse mapping is available for regular numeric enums, not string enums.
9. Practical Example: Course Enrollment
A training application can use enums to represent course enrollment statuses consistently throughout the application.
Example
enum EnrollmentStatus {
Registered = "REGISTERED",
InProgress = "IN_PROGRESS",
Completed = "COMPLETED"
}
interface Enrollment {
studentName: string;
courseName: string;
status: EnrollmentStatus;
}
const enrollment1: Enrollment = {
studentName: "Rahul",
courseName: "TypeScript",
status: EnrollmentStatus.InProgress
};
console.log(enrollment1.studentName);
console.log(enrollment1.courseName);
console.log(enrollment1.status);
Expected Output
Rahul
TypeScript
IN_PROGRESS
How It Works
EnrollmentStatus
Defines the permitted enrollment states.
Enrollment Object
Stores student, course and status details.
Type Checking
Checks that status is an allowed enum member.
10. Important Rules of Enums
| Rule | Explanation |
|---|---|
| Numeric enum default | Automatically starts at 0 when no initial value is supplied. |
| Custom numeric values | Members can be assigned specific numeric values. |
| String enum values | String members must be explicitly assigned string values. |
| Member access | Use the enum name followed by a dot and the member name. |
| Numeric reverse mapping | Regular numeric enums support lookup from number to member name. |
| Runtime representation | Regular enums generate JavaScript runtime code; they are not just type-only declarations. |
11. Advantages of Enums
Readable Code
Meaningful names are easier to understand than unexplained values.
Consistency
Related values are grouped under a common enum name.
Maintainability
Centralizes related named values for reuse throughout the codebase.
Clear Conditions
Works well with conditions and switch statements.
Summary
Enums group related named constants. Numeric enums can assign numbers automatically or through custom values, while string enums require explicit string assignments. Enum members can be used in variables, conditions, switch statements and object properties.
Next, learn Literal Types and how to restrict variables to specific string, number or boolean values.