7️⃣ 🔁 TypeScript Control Flow & Decision Making
Estimated reading: 4 minutes 447 views

TypeScript — Switch Statement: Structured Multi-Condition Control Flow

Introduction – What Is a Switch Statement in TypeScript?

In TypeScript, the switch statement is a control structure used to execute one block of code from multiple possible cases based on the value of a variable or expression. It works similarly to JavaScript’s switch but with the added benefit of type safety and type narrowing, thanks to TypeScript’s static typing system.

Unlike chained if...else statements, a switch provides a cleaner and more organized way to handle multiple distinct values—especially when dealing with enums, string unions, or discriminated union types.

In this guide, you’ll learn:

  • Basic syntax of the switch statement
  • How to use switch with strings, numbers, enums, and union types
  • TypeScript-specific features like type narrowing
  • Real-world use cases and best practices

Basic Syntax of Switch Statement

switch (expression) {
  case value1:
    // code block
    break;
  case value2:
    // code block
    break;
  default:
    // default code block
}

Example:

const day = "Tuesday";

switch (day) {
  case "Monday":
    console.log("Start of the workweek");
    break;
  case "Friday":
    console.log("End of the workweek");
    break;
  default:
    console.log("It's just a regular day");
}

Tip: The break statement prevents fall-through between cases.


Using Switch with Numbers

function getGrade(score: number): string {
  switch (score) {
    case 100:
      return "Perfect!";
    case 90:
      return "Excellent";
    case 70:
      return "Good";
    default:
      return "Try Again";
  }
}

Switch with Enums

Enums are commonly used with switch statements in TypeScript for cleaner and more readable logic.

enum UserRole {
  Admin,
  Editor,
  Viewer
}

function checkAccess(role: UserRole) {
  switch (role) {
    case UserRole.Admin:
      console.log("Full access granted");
      break;
    case UserRole.Editor:
      console.log("Edit access granted");
      break;
    case UserRole.Viewer:
      console.log("Read-only access granted");
      break;
    default:
      console.log("Unknown role");
  }
}

Benefit: Enum values are type-checked at compile time.


Switch with String Literal Union Types

TypeScript allows you to use switch effectively with union types for exhaustive checks.

type Status = "success" | "error" | "loading";

function renderStatus(status: Status): void {
  switch (status) {
    case "success":
      console.log("Operation successful");
      break;
    case "error":
      console.log("An error occurred");
      break;
    case "loading":
      console.log("Loading...");
      break;
    default:
      // Using `never` ensures all cases are handled
      const exhaustiveCheck: never = status;
      throw new Error(`Unhandled status: ${exhaustiveCheck}`);
  }
}

This approach ensures type safety by forcing all possible values to be covered.


Common Mistakes and How to Avoid Them

Mistake Solution
Forgetting break after casesUse break to avoid unintended fall-through
Not handling all enum/union valuesUse a default block or an exhaustive never check
Using complex expressions in casesUse simple constants or variables for comparison
Repeating code in multiple casesGroup cases or refactor into functions

Best Practices for Using Switch in TypeScript

  • Use switch for multiple distinct values instead of long if...else if chains
  • Combine with enums or union types for compile-time checks
  • Use the default case to catch unexpected input
  • Leverage never type for exhaustive checking in union types
  • Format your code clearly for readability and maintainability

Real-World Use Cases

  • API response handling based on status
  • User role-based access control
  • Routing based on query parameters or actions
  • Form mode switching (view, edit, preview)
  • Command handling in chatbots or CLIs

Summary – Recap & Takeaways

The switch statement in TypeScript is a powerful control structure that provides a cleaner alternative to complex if...else logic. When used with enums and union types, it ensures type safety, exhaustiveness, and maintainability in your code.

Key Takeaways:

  • TypeScript’s switch works like JavaScript but adds type safety
  • Use break after each case to prevent fall-through
  • Leverage enums or string union types for clean and safe condition handling
  • Always include a default case or an exhaustive never check
  • Ideal for use cases involving fixed sets of known values

Practical relevance: Switch statements are widely used in form logic, role handling, routing, state machines, and UI render decisions.


FAQs – TypeScript Switch Statement

Is the switch statement type-checked in TypeScript?
Yes. When used with enums or union types, TypeScript ensures type-safe comparisons.

Do I need to include a break in every case?
It is strongly recommended to prevent fall-through behavior.

Can I use switch with union types?
Yes, and TypeScript will enforce exhaustive checking when used correctly.

What happens if a switch case is not matched?
The default case (if present) will execute.

How can I ensure all union cases are handled?
Use a never check in the default block to catch unhandled values during compilation.


Share Now :
Share

TypeScript — Switch Statement

Or Copy Link

CONTENTS
Scroll to Top