Lessons
TypeScript Tutorial
TypeScript Control Structures
TypeScript Function Types
TypeScript Switch Case
If we have a conditional statements if and if-else then why do we need a switch case statement? Decision-making is an integral part of programming. When dealing with multiple conditions that depend on the value of a single variable, using multiple if-else
statements can become cumbersome and hard to read. This is where the switch case
statement in TypeScript becomes an excellent alternative. It simplifies decision-making by evaluating a single expression and executing code blocks based on its value.
For example:
Assigning roles based on user input.
Responding to different statuses in an application.
Executing specific logic for different configurations.
By replacing multiple if-else
blocks, the switch case
improves readability and ensures better performance in some cases.
What is a TypeScript Switch Case Statement?
The switch case
statement evaluates a single expression (like a variable or function result) and compares its value against multiple predefined cases. If a match is found, the corresponding block of code is executed. If no match is found, an optional default
case can handle all unmatched scenarios.
Key Features:
- Handles multiple conditions for a single expression.
- Makes code more structured and easier to follow.
- Includes a
default
case to handle unexpected or unmatched values.
Syntax of Switch Case in TypeScript
The switch case
statement follows a straightforward syntax:
tsx
1 2 3 4 5 6 7 8 9 10
switch (expression) { case value1: // Code to execute if expression === value1 break; case value2: // Code to execute if expression === value2 break; default: // Code to execute if no case matches }
Key Components:
switch (expression)
: The expression being evaluated.case value:
: A specific value to compare the expression against.break
: Terminates the current case block to prevent falling through to the next case.default:
: An optional block that executes if none of thecase
values match.
TypeScript Switch Case Statement Examples
Let's explore each scenario step by step:
Example 1: Handling Days of the Week
You want to display a message based on the day of the week.
tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
let day = "Monday"; // Initialize the variable with the current day switch (day) { case "Monday": // Check if the day is Monday console.log("Start of the work week."); // Log a message for Monday break; // Exit the switch after executing this case case "Friday": // Check if the day is Friday console.log("Almost the weekend!"); // Log a message for Friday break; // Exit the switch after executing this case case "Saturday": // Check if the day is Saturday case "Sunday": // Check if the day is Sunday (grouped with Saturday) console.log("It's the weekend!"); // Log a message for weekends break; // Exit the switch after executing this case default: // Handle all other days not explicitly listed above console.log("A regular weekday."); // Log a default message for regular we
Explanation:
- Variable Initialization:
- The variable
day
is assigned the value"Monday"
. This represents the day we want to evaluate.
- The variable
- Switch Statement:
- The
switch
evaluates the value ofday
and compares it with the values listed in thecase
blocks.
- The
- Case "Monday":
- If the value of
day
is"Monday"
, the message "Start of the work week." is logged to the console. - The
break
statement ensures the code exits theswitch
block and does not continue checking other cases.
- If the value of
- Case "Friday":
- If
day
is"Friday"
, the message "Almost the weekend!" is logged to the console. - Again, the
break
statement prevents further execution of other cases.
- If
- Cases "Saturday" and "Sunday":
- These two cases are grouped. If the value of
day
is either"Saturday"
or"Sunday"
, the message "It's the weekend!" is logged. - Grouping cases eliminates redundancy when multiple conditions lead to the same outcome.
- These two cases are grouped. If the value of
- Default Case:
- If the value of
day
does not match any of the listed cases, thedefault
block executes. - This acts as a fallback, logging "A regular weekday." for all other days.
- If the value of
- Importance of
break
:- The
break
statements prevent "fall-through," where the code continues executing subsequent cases even after finding a match. - Without
break
, all cases after a matching one would execute, which can lead to unintended behavior.
- The
Best Practices for Using Switch Case in TypeScript
Following these practices helps you maximize the benefits of the switch case
statement.
- Group Cases When Appropriate: Combine cases with the same outcome to reduce redundancy (e.g., weekend days in Example 1).
- Use Default Case: Always include a
default
case to handle unexpected values and improve robustness. - Avoid Overusing Switch Statements: For simple conditions,
if-else
or ternary operators may be more appropriate. - Keep Cases Simple: Avoid including complex logic within cases. Instead, call functions for better readability and maintainability.
- Use TypeScript’s Type Checking: Ensure the
expression
being evaluated andcase
values are of compatible types.