TS Enums

TypeScript Enums

An Enum (short for Enumeration) is a special class that represents a group of constants.

Enums allow you to define a collection of named, related, and unchangeable values.

They make your code incredibly readable when dealing with states or categories.

TypeScript supports both numeric and string-based enums easily.


1. Numeric Enums

By default, enums are numeric and automatically start counting from zero.

The first item gets the value 0, the second gets 1, and so on.

This is highly memory efficient and great for tracking simple application states.

Numeric Enum Example:

enum Direction {
  Up,    // 0
  Down,  // 1
  Left,  // 2
  Right  // 3
}

let currentMove: Direction = Direction.Up;

console.log("Current move direction value:", currentMove);


2. String Enums

String enums are often preferred because they are far more readable when debugging.

Instead of assigning numbers, you explicitly assign a string value to each key.

If you log a string enum to the console, you will see a meaningful word, not just a number.

String Enum Example:

enum Status {
  Pending = "PENDING",
  Approved = "APPROVED",
  Rejected = "REJECTED"
}

let orderStatus = Status.Approved; console.log(orderStatus); // Outputs: APPROVED


3. SEO and Maintainability

Using Enums replaces "magic strings" and random numbers spread throughout your code.

This greatly reduces bugs and improves the maintainability of large projects.

High-quality, bug-free sites perform substantially better in SEO metrics over time.

Best Practice Example:

enum Roles {
  Admin = 1,
  User = 2,
  Guest = 3
}
// You can manually set the starting number, and it auto-increments!

console.log("Admin Role ID:", Roles.Admin);


Exercise

?

What is the default starting value of a numeric enum in TypeScript?


4. Final Thoughts

Enums are a powerful organizational tool borrowed directly from C# and Java.

They bring serious structure to your everyday JavaScript variables.

Next up, we will learn how to create reusable Types and Interfaces!