Enums: Named Sets of Constants
An enum gives friendly names to a fixed group of related values, so your code reads clearly.
What you will learn
- Define and use a numeric enum
- Use a string enum for readable values
- Choose between an enum and a literal union
Names instead of mystery values
Code is full of fixed sets: directions, roles, statuses. Instead of remembering "0 means North", an enum lets you use a clear name like Direction.North.
enum Direction {
North, // 0
East, // 1
South, // 2
West // 3
}
let heading: Direction = Direction.East;
console.log(heading);
console.log(Direction[1]); // look up the nameNote: Output:
1
East
By default enum members get numbers starting at 0, so Direction.East is 1. You can also look up the name from the number with Direction[1].
String enums — readable everywhere
Numbers can be cryptic in logs and databases. A string enum stores a readable word for each member:
enum Status {
Active = 'ACTIVE',
Paused = 'PAUSED',
Closed = 'CLOSED'
}
let s: Status = Status.Active;
console.log('Account is ' + s);Note: Output: Account is ACTIVE Now the value is the clear string 'ACTIVE' instead of a number. This is easier to read in logs and safer to store.
Using an enum in real code
Enums are most useful as the type of a parameter. The function below only accepts a valid Status, and the editor will suggest the members for you while you type:
enum Status {
Active = 'ACTIVE',
Paused = 'PAUSED',
Closed = 'CLOSED'
}
function message(status: Status): string {
switch (status) {
case Status.Active: return 'Your account is live.';
case Status.Paused: return 'Your account is on hold.';
case Status.Closed: return 'Your account is closed.';
}
}
console.log(message(Status.Paused));Note: Output:
Your account is on hold.
The parameter type Status means you cannot pass a random string by mistake — only Status.Active, Status.Paused or Status.Closed. Passing 'ACTIVE' as a plain string would be rejected.
Enum or literal union?
A literal union (from earlier) can do a similar job. Here is how to choose:
| Want | Pick |
|---|---|
| A simple set of allowed strings | Literal union — lighter, no extra JS |
A named group you reference as X.Member | Enum |
| Reverse lookup (name from number) | Numeric enum |
| Smallest compiled output | Literal union |
Tip: Beginners often start with literal unions ('active' | 'paused') because they are simpler and add no code at runtime. Reach for enums when you want a named, grouped set you refer to as Status.Active.
Q. In enum Direction { North, East }, what is the value of Direction.East?
✍️ Practice
- Create a numeric
enum Day { Mon, Tue, Wed }and print the value ofDay.Wed. - Create a string
enum Role { Admin = 'ADMIN', User = 'USER' }and log a role.
🏠 Homework
- Make a string enum for traffic lights (Red, Yellow, Green) and a function that returns advice for each colour.