TypeScript Switch Case With Enums

When working on TypeScript applications, especially in larger projects, using switch statements with enums can significantly enhance the code’s maintainability.

Recently, while building features for a web app that involved managing user roles and order statuses, I came to know about the use of enums in handling a fixed set of related values. I learned that pairing enums with exhaustive switch cases using the never type helps prevent errors when new enum values are added.

In this TypeScript tutorial, I will explain how to handle switch case with Enums in TypeScript.

What Are Enums in TypeScript?

Enums, short for enumerations, are a feature in TypeScript that allows you to define a set of named constants. They are a way to group related values together, making your code more readable and organized. Enums can be numeric or string-based and are particularly useful when you have a fixed set of related values that you want to represent as distinct types.

Types of Enums

  1. Numeric Enums: These are the default type of enums in TypeScript, where each member is assigned a numeric value.
  2. String Enums: These enums assign string values to each member.
  3. Heterogeneous Enums: These enums can contain both string and numeric values.

Why Use Enums with Switch Case in TypeScript?

Using enums with switch case statements provides several benefits:

  • Readability: Enums make your code more readable by providing meaningful names for values.
  • Maintainability: Enums make it easier to manage and update your code by centralizing related constants.
  • Type Safety: Enums enhance type safety by ensuring that only valid values are used in your code.

Check out: Use TypeScript Enums in Classes

Implementing Enums in Switch Case Statements

Let’s explore some practical examples to see how enums can be utilized in switch case statements.

Example 1: Handling User Roles

Imagine you are developing a web application for a company in New York City. You need to handle different user roles such as Admin, User, and Guest. Here’s how you can use enums with switch case statements to manage these roles:

enum UserRole {
    Admin = 'Admin',
    User = 'User',
    Guest = 'Guest'
}

function getPermissions(role: UserRole) {
    switch (role) {
        case UserRole.Admin:
            return 'Full Access';
        case UserRole.User:
            return 'Limited Access';
        case UserRole.Guest:
            return 'Read Only Access';
        default:
            return 'No Access';
    }
}

console.log(getPermissions(UserRole.Admin)); // Output: Full Access
console.log(getPermissions(UserRole.Guest)); // Output: Read Only Access

Output:

Switch Case in TypeScript Enum

Check out: Check Enum Equality in TypeScript

Example 2: Managing Order Status

Consider an e-commerce platform based in Los Angeles where you need to handle different order statuses such as Pending, Shipped, Delivered, and Cancelled. Here’s how you can implement this using enums:

enum OrderStatus {
    Pending = 'Pending',
    Shipped = 'Shipped',
    Delivered = 'Delivered',
    Cancelled = 'Cancelled'
}

function getOrderStatusMessage(status: OrderStatus) {
    switch (status) {
        case OrderStatus.Pending:
            return 'Your order is pending.';
        case OrderStatus.Shipped:
            return 'Your order has been shipped.';
        case OrderStatus.Delivered:
            return 'Your order has been delivered.';
        case OrderStatus.Cancelled:
            return 'Your order has been cancelled.';
        default:
            return 'Unknown status.';
    }
}

console.log(getOrderStatusMessage(OrderStatus.Shipped)); // Output: Your order has been shipped.

Output:

Enums in Switch Case in TypeScript

Ensuring Exhaustive Checks with Enums in TypeScript

One of the challenges with switch case statements is ensuring that all possible enum values are handled. TypeScript provides a way to enforce exhaustive checks at compile time, which can help you catch errors early.

Using the Never Type

The never type in TypeScript can be used to ensure that all enum values are handled. If a value is not handled, TypeScript will throw a compile-time error.

enum PaymentStatus {
    Pending = 'Pending',
    Completed = 'Completed',
    Failed = 'Failed'
}

function handlePaymentStatus(status: PaymentStatus): string {
    switch (status) {
        case PaymentStatus.Pending:
            return 'Payment is pending.';
        case PaymentStatus.Completed:
            return 'Payment completed successfully.';
        case PaymentStatus.Failed:
            return 'Payment failed.';
        default:
            const exhaustiveCheck: never = status;
            return exhaustiveCheck;
    }
}

Output:

Handle Enum Switch Case in Typescript

In this example, if a new value is added to the PaymentStatus enum and not handled in the switch case, TypeScript will throw an error, ensuring that all values are accounted for.

Check out: Difference Between Enums vs String Literal Unions in TypeScript

Best Practices for Using Enums with Switch Case

1. Use Meaningful Names

Always use meaningful names for your enum members to make your code more readable and self-explanatory.

2. Centralize Enum Definitions

Define your enums in a central location, such as a separate file, to make them easy to manage and update.

3. Use String Enums for Better Debugging

String enums can be more readable and easier to debug compared to numeric enums, especially when logging or displaying enum values.

4. Ensure Exhaustive Checks

Use the never type to ensure that all possible enum values are handled in your switch case statements.

Conclusion

I hope this tutorial gave you a clear understanding of how to use enums with switch case statements in TypeScript. Whether you’re handling user roles, order statuses, or payment flows, enums can help you write cleaner, more organized, and type-safe code.

By following the examples and best practices shared here, like using string enums and ensuring exhaustive checks, you can avoid common runtime errors and improve the overall maintainability of your applications.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.