Understand TypeScript Switch Statements

In my recent TypeScript project, I’ve used switch statements whenever I need to handle multiple values of a single variable, like checking state codes, user roles, or order statuses. It helps me avoid repeating the same if-else statements in my code.

I prefer switch statements when I know the variable can take on a fixed set of values, and I want to run different code for each one.

In this tutorial, I’ll explain how to use TypeScript switch statements with the help of real-time examples.

What is a Switch Statement in TypeScript?

A switch statement in TypeScript evaluates an expression and matches it against multiple case clauses. It’s similar to the switch statement in JavaScript but with added type safety.

I often use switch statements when I need to perform different actions based on a single variable’s value. For example, processing different user roles in a web application or handling various API response codes.

Basic Syntax of TypeScript Switch Statement

The basic structure of a switch statement in TypeScript looks like this:

switch (expression) {
  case value1:
    // Code to execute when expression equals value1
    break;
  case value2:
    // Code to execute when expression equals value2
    break;
  default:
    // Code to execute when none of the cases match
    break;
}

Let me explain this with a practical example. Imagine we’re building a weather app for American cities:

function getWeatherAdvice(temperature: number): string {
  switch (true) {
    case temperature < 32:
      return "It's freezing! Wear a heavy coat and gloves.";
    case temperature < 50:
      return "It's cold. Bring a jacket.";
    case temperature < 70:
      return "It's mild. A light sweater should be fine.";
    case temperature < 90:
      return "It's warm. T-shirt weather!";
    default:
      return "It's hot! Stay hydrated and find some shade.";
  }
}

// Example usage
console.log(getWeatherAdvice(28)); // It's freezing! Wear a heavy coat and gloves.
console.log(getWeatherAdvice(65)); // It's mild. A light sweater should be fine.

Output:

Switch Statements in TypeScript

Check out: Convert TypeScript Objects to JSON

The Importance of the break Statement

In my early days with TypeScript, I made a common mistake of forgetting the break statement. Without it, execution “falls through” to the next case, which rarely is what you want.

Here’s an example showing what happens without break statements:

function demonstrateFallthrough(stateCode: string): string {
  let taxes = 0;

  switch (stateCode) {
    case "CA":
      taxes += 7.25; // California base sales tax
    case "TX":
      taxes += 6.25; // Texas base sales tax
    case "NY":
      taxes += 4.0; // New York base sales tax
    case "FL":
      taxes += 6.0; // Florida base sales tax
    default:
      taxes += 5.0; // Default tax
  }

  return `Tax rate: ${taxes}%`;
}

console.log(demonstrateFallthrough("CA")); // Tax rate: 28.5%

Output:

Use Break Statement in typeScript switch case

This is clearly not what we want! The correct implementation with breaks would be:

function calculateTax(stateCode: string): number {
  switch (stateCode) {
    case "CA":
      return 7.25;
    case "TX":
      return 6.25;
    case "NY":
      return 4.0;
    case "FL":
      return 6.0;
    default:
      return 5.0;
  }
}

Output:

Break Statement in TypeScript Switch Case

Check out: TypeScript keyof Operator

Using Multiple Cases for the Same Code Block

Sometimes, I need to execute the same code for multiple case values. TypeScript allows grouping cases like this:

function getRegionFromState(state: string): string {
  switch (state) {
    case "ME":
    case "NH":
    case "VT":
    case "MA":
    case "RI":
    case "CT":
      return "New England";

    case "NY":
    case "NJ":
    case "PA":
      return "Mid-Atlantic";

    case "FL":
    case "GA":
    case "SC":
    case "NC":
    case "VA":
      return "Southeast";

    default:
      return "Other US Region";
  }
}

console.log(getRegionFromState("MA")); // New England
console.log(getRegionFromState("PA")); // Mid-Atlantic

Output:

TypeScript Switch Statement for multiple cases

Check out: TypeScript Type Casting

Switch Statements with Expressions

One powerful feature of TypeScript switch statements is the ability to use expressions in the case clauses. I use this technique when I need more complex condition checking:

function getStudentGrade(score: number): string {
  switch (true) {
    case score >= 90:
      return "A";
    case score >= 80:
      return "B";
    case score >= 70:
      return "C";
    case score >= 60:
      return "D";
    default:
      return "F";
  }
}

console.log(getStudentGrade(85)); // B
console.log(getStudentGrade(72)); // C

Output:

Switch Statements with Expressions in TypeScript

Check out: Spread Operator in TypeScript

Using Enums with Switch Statements

TypeScript’s enum type works exceptionally well with switch statements. I often use this combination to handle different application states:

enum OrderStatus {
  Pending,
  Processing,
  Shipped,
  Delivered,
  Cancelled
}

function getOrderStatusMessage(status: OrderStatus): string {
  switch (status) {
    case OrderStatus.Pending:
      return "Your order has been received and is awaiting processing.";
    case OrderStatus.Processing:
      return "Your order is being processed and will ship soon.";
    case OrderStatus.Shipped:
      return "Your order has been shipped and is on its way!";
    case OrderStatus.Delivered:
      return "Your order has been delivered. Enjoy!";
    case OrderStatus.Cancelled:
      return "Your order has been cancelled.";
    default:
      const exhaustiveCheck: never = status;
      return `Unknown status: ${exhaustiveCheck}`;
  }
}

console.log(getOrderStatusMessage(OrderStatus.Shipped)); // Your order has been shipped and is on its way!

Output:

Enums with Switch statements in TypeScript

Notice the exhaustiveCheck variable in the default case. This is a technique I use to ensure type safety – TypeScript will give a compile-time error if we add a new enum value but forget to handle it in the switch statement.

Switch Statement with String Literal Types

TypeScript’s string literal types add another layer of type safety to switch statements:

type USTimeZone = "Eastern" | "Central" | "Mountain" | "Pacific" | "Alaska" | "Hawaii";

function getTimeZoneOffset(zone: USTimeZone): string {
  switch (zone) {
    case "Eastern":
      return "UTC-5:00 (UTC-4:00 during DST)";
    case "Central":
      return "UTC-6:00 (UTC-5:00 during DST)";
    case "Mountain":
      return "UTC-7:00 (UTC-6:00 during DST)";
    case "Pacific":
      return "UTC-8:00 (UTC-7:00 during DST)";
    case "Alaska":
      return "UTC-9:00 (UTC-8:00 during DST)";
    case "Hawaii":
      return "UTC-10:00 (no DST)";
  }
}

console.log(getTimeZoneOffset("Pacific")); // UTC-8:00 (UTC-7:00 during DST)

Output:

Switch Statement with String Literal Types in TypeScript

Check out: TypeScript Type Narrowing

Switch Statements vs. Object Lookups

In some cases, I find that using an object lookup is more efficient than a switch statement:

type USState = "NY" | "CA" | "TX" | "FL" | "IL";

// Using a switch statement
function getStateCapitalWithSwitch(state: USState): string {
  switch (state) {
    case "NY": return "Albany";
    case "CA": return "Sacramento";
    case "TX": return "Austin";
    case "FL": return "Tallahassee";
    case "IL": return "Springfield";
  }
}

// Using an object lookup
function getStateCapitalWithObject(state: USState): string {
  const capitals: Record<USState, string> = {
    NY: "Albany",
    CA: "Sacramento",
    TX: "Austin",
    FL: "Tallahassee",
    IL: "Springfield"
  };

  return capitals[state];
}

Both approaches work, but the object lookup is often more concise. I typically use switch statements when I need to execute more complex logic for each case.

Advanced Pattern: Switch Statement with Pattern Matching

TypeScript doesn’t have built-in pattern matching like some functional languages, but I’ve developed a technique to simulate it:

type UserAction = 
  | { type: "LOGIN", username: string, password: string }
  | { type: "LOGOUT" }
  | { type: "UPDATE_PROFILE", fields: { name?: string, email?: string, phone?: string } };

function handleUserAction(action: UserAction): string {
  switch (action.type) {
    case "LOGIN":
      return `Attempting to log in user ${action.username}`;

    case "LOGOUT":
      return "Logging out current user";

    case "UPDATE_PROFILE":
      const fieldsToUpdate = Object.keys(action.fields).join(", ");
      return `Updating user profile: ${fieldsToUpdate || "no fields provided"}`;
  }
}

console.log(handleUserAction({ type: "LOGIN", username: "john_doe", password: "secure123" }));
// Attempting to log in user john_doe

console.log(handleUserAction({ type: "UPDATE_PROFILE", fields: { name: "John Doe", email: "john@example.com" } }));
// Updating user profile: name, email

Output:

Switch Statement with Pattern Matching in TypeScript

This approach leverages TypeScript’s discriminated unions to provide type safety across different action shapes.

Check out: Typescript Iterate Over Records

Common Mistakes and How to Avoid Them

After years of working with TypeScript, I’ve noticed some common mistakes with switch statements:

  1. Forgetting the break statement: Always add a break (or return) at the end of each case unless you specifically want fallthrough behavior.
  2. Not handling all cases: When switching on an enum or union type, make sure to handle all possible values or include a default case.
  3. Using expressions without ‘true’: When using expressions in case conditions, remember to switch on true.
  4. Complex logic in case statements: Keep each case simple; if you need complex logic, extract it to a separate function.

Check out: Use TypeScript Environment Variables

TypeScript switch statements are a powerful tool when used correctly. They provide a clean way to handle multiple conditions and, with TypeScript’s type system, offer additional safety guarantees.

I hope you understood how switch statements work in TypeScript and why they’re useful when handling multiple values based on one variable. We’ve learned about different use case scenarios of switch statements in examples, such as calculating tax, checking grades, and managing user actions.

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.