← Back to TypeScript Course | Chapter 2: Basic Types | Lesson 5 of 11

Enum Types

An enum lets you define a set of named constants. Enums can make code easier to read when a value must come from a known group of choices.

Numeric Enums

A numeric enum assigns a numeric value to each of its members, and by default the first member starts at zero with each later member incrementing automatically. You can also set the starting value explicitly, and the rest will count up from there.

Example: Numeric Enums

typescript
enum Direction {
  Up,
  Down,
  Left,
  Right,
}
console.log(Direction.Up, Direction.Right);

String Enums

String enums give each member an explicit string value instead of an auto-incrementing number, written directly in the enum definition. They're often easier to debug because logging or serializing the value shows a meaningful word rather than an opaque number.

Example: String Enums

typescript
enum Status {
  Active = "ACTIVE",
  Inactive = "INACTIVE",
}
console.log(Status.Active);

Using Enums in Functions

Enums can be used directly as a function parameter's type, which restricts callers to only the values actually defined in that enum. This prevents a caller from passing an arbitrary number or string where only one of a known, fixed set of options makes sense.

Example: Using Enums in Functions

typescript
enum Role {
  Admin,
  Editor,
  Viewer,
}
function checkAccess(role: Role): void {
  console.log(`Access level: ${Role[role]}`);
}
checkAccess(Role.Admin);

Enum Comparisons

Enum members can be compared using the normal equality operators, just like any other value, since each member is really just a constant under the hood. This makes it easy to branch program behavior based on which known enum value is currently held.

Example: Enum Comparisons

typescript
enum Status {
  Active,
  Inactive,
}
let current: Status = Status.Active;
console.log(current === Status.Active);

Enums in Switch Statements

Enums pair especially well with switch statements, since each case label can represent exactly one known enum member. This keeps code that needs to handle several distinct states organized and makes it easy to see at a glance whether every option is covered.

Example: Enums in Switch Statements

typescript
enum Status {
  Active,
  Inactive,
  Pending,
}
let current: Status = Status.Pending;
switch (current) {
  case Status.Active:
    console.log("Active");
    break;
  case Status.Pending:
    console.log("Pending");
    break;
  default:
    console.log("Other");
}
🔒

Chapter Quiz — Complete all 11 topics to unlock

0/11 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.