Enums in TypeScript

Explore enums and how they can be used to define a set of named constants. Learn about numeric and string enums.


TypeScript Enums for Beginners

Enums (short for "enumerations") are a powerful feature in TypeScript that allow you to define a set of named constants. They're essentially a way to give meaningful names to numerical or string values, making your code more readable and maintainable. Think of them like creating custom data types for a limited set of possible values.

What are Enums?

Imagine you're working with days of the week. Instead of using numbers like 0, 1, 2, etc., or strings like "Monday", "Tuesday", etc., you can define an enum:

 enum DayOfWeek {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
} 

Now, you can use DayOfWeek.Monday instead of a magic number or a string. This makes your code easier to understand and less prone to errors.

Numeric Enums

By default, TypeScript assigns numbers to enum members, starting from 0. This means that in the DayOfWeek example above:

  • DayOfWeek.Sunday is 0
  • DayOfWeek.Monday is 1
  • DayOfWeek.Tuesday is 2
  • and so on...

You can also explicitly assign numbers to enum members. For example:

 enum StatusCode {
    OK = 200,
    NotFound = 404,
    InternalServerError = 500
}

console.log(StatusCode.OK); // Output: 200 

If you only assign a number to the first member, subsequent members will automatically increment from that value:

 enum CardinalDirection {
    North = 1,
    East,  // Automatically becomes 2
    South, // Automatically becomes 3
    West   // Automatically becomes 4
}

console.log(CardinalDirection.East); // Output: 2 

String Enums

In addition to numeric enums, you can also create string enums. With string enums, each member must be explicitly initialized with a string value.

 enum LogLevel {
    Debug = "DEBUG",
    Info = "INFO",
    Warning = "WARNING",
    Error = "ERROR"
}

function logMessage(message: string, level: LogLevel) {
    console.log(`[${level}] ${message}`);
}

logMessage("Something happened!", LogLevel.Error); // Output: [ERROR] Something happened! 

String enums are generally considered more readable and prevent accidental misuse because TypeScript enforces that you use the defined string values.

Why Use Enums?

  • Readability: Enums provide meaningful names to values, making your code easier to understand.
  • Maintainability: If you need to change a value, you only need to change it in the enum definition, rather than searching and replacing throughout your code.
  • Type Safety: TypeScript's type system helps ensure that you only use valid enum values, reducing the risk of errors.
  • Autocompletion: IDEs can provide autocompletion suggestions for enum members, making coding faster and less error-prone.

Example: Using Enums in a Function

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

function grantAccess(userRole: UserRole): string {
    switch (userRole) {
        case UserRole.Admin:
            return "Full access granted.";
        case UserRole.Editor:
            return "Editor access granted.";
        case UserRole.Viewer:
            return "Viewer access granted.";
        default:
            return "No access granted.";
    }
}

console.log(grantAccess(UserRole.Admin)); // Output: Full access granted. 

In this example, the grantAccess function uses the UserRole enum to determine the appropriate access level for a user. The switch statement is more readable and maintainable than using string comparisons.

Key Takeaways

  • Enums are a way to define a set of named constants in TypeScript.
  • They can be numeric or string-based.
  • Numeric enums are automatically assigned numbers starting from 0 (or a specified starting value).
  • String enums require explicit string values for each member.
  • Enums improve code readability, maintainability, and type safety.