TypeScript Enums

Named constants for better code readability

🔢 What are Enums?

Enums (Enumerations) allow you to define a set of named constants, making your code more readable and maintainable. They're perfect for representing fixed sets of values like days, directions, or status codes.


// Simple enum example
enum Direction {
    Up,
    Down,
    Left,
    Right
}

let move: Direction = Direction.Up;
                                    

Types of Enums

🔢

Numeric Enums

Default enum type with numbers

enum Status {
    Pending,    // 0
    Active,     // 1
    Completed   // 2
}
📝

String Enums

Enums with string values

enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE"
}
🔀

Heterogeneous

Mix of string and number

enum Mixed {
    No = 0,
    Yes = "YES"
}

Const Enums

Optimized enums

const enum Size {
    Small,
    Medium,
    Large
}

🔹 Numeric Enums

Numeric enums auto-increment from 0 by default:

enum Level {
    Beginner,      // 0
    Intermediate,  // 1
    Advanced,      // 2
    Expert         // 3
}

let myLevel: Level = Level.Intermediate;
console.log(myLevel);  // Output: 1
console.log(Level[1]); // Output: "Intermediate"

Output:

1

Intermediate

🔹 Custom Numeric Values

You can set custom starting values:

enum HttpStatus {
    OK = 200,
    Created = 201,
    BadRequest = 400,
    NotFound = 404,
    ServerError = 500
}

let status: HttpStatus = HttpStatus.NotFound;
console.log(status); // Output: 404

Output:

404

🔹 String Enums

String enums provide more meaningful values:

enum UserRole {
    Admin = "ADMIN",
    Editor = "EDITOR",
    Viewer = "VIEWER"
}

function checkPermission(role: UserRole) {
    if (role === UserRole.Admin) {
        return "Full access granted";
    }
    return "Limited access";
}

console.log(checkPermission(UserRole.Admin));

Output:

Full access granted

🔹 Reverse Mapping

Numeric enums support reverse mapping (value to name):

enum Day {
    Monday = 1,
    Tuesday,
    Wednesday
}

console.log(Day.Monday);    // Output: 1
console.log(Day[1]);        // Output: "Monday"
console.log(Day[2]);        // Output: "Tuesday"

Output:

1

Monday

Tuesday

🔹 Const Enums

Const enums are removed during compilation for better performance:

const enum Theme {
    Light = "light",
    Dark = "dark",
    Auto = "auto"
}

let currentTheme = Theme.Dark;
// Compiles to: let currentTheme = "dark";

Benefits of Const Enums:

  • No extra JavaScript code generated
  • Values are inlined at compile time
  • Better performance
  • Smaller bundle size

🔹 Practical Example

Using enums in a real-world scenario:

enum OrderStatus {
    Pending = "PENDING",
    Processing = "PROCESSING",
    Shipped = "SHIPPED",
    Delivered = "DELIVERED",
    Cancelled = "CANCELLED"
}

interface Order {
    id: number;
    status: OrderStatus;
}

function updateOrder(order: Order, newStatus: OrderStatus) {
    order.status = newStatus;
    console.log(`Order ${order.id} is now ${newStatus}`);
}

let myOrder: Order = { id: 123, status: OrderStatus.Pending };
updateOrder(myOrder, OrderStatus.Shipped);

Output:

Order 123 is now SHIPPED

🧠 Test Your Knowledge

What is the default starting value for numeric enums?