Switch in TypeScript

Learn via video courses
Topics Covered

Overview

The switch statement evaluates an expression, matches the value of the expression to a case clause, and executes the statements associated with that case, as well as statements in cases that follow the matching case.

Introduction to TypeScript Switch Case

Switch case in TypeScript is used to execute one statement from multiple conditions. The switch statement takes an expression and evaluates it with defined valid cases, and then returns the values associated with the case that matches the expression.

For example, We are making a website that displays the days of the week. The website will simply take any number from 1 to 7 as input and return the day associated with it. Hence, if we try to achieve the above situation with the help of an if-else statement, we have to write seven if statements where we'll compare the variable with the number associated with each day of the week. As we can see the above process is complex, this type of situation can be handled by the Switch case.

Syntax of Switch Case

In the above syntax, if the expression value is equal to val1 then only the code block statement1 will be executed. We use break after every case as it is required to not execute other block statements. The default case will be executed when the expression doesn't match with any other case. The default can come in any order but it is always executed at the last after all the cases are evaluated.

Rules that Apply to a Switch Statement

Various rules are applied on switch Statement in TypeScript:

  • The switch statement may have constant or variable expressions that return a value of any data type.
  • The break statement should be used at the end of each case block to stop the execution of the case block.
  • The return type of the case expression and switch expression should match.
  • The case expression must be unique.
  • In the switch expression, the default block is optional.
  • The case can have a constant or an expression and there can be any number of case statements within a switch.

Flowchart of Switch Case

Following is the flowchart that demonstrated the working of the Switch case in TypeScript:

Switch Case Flowchart

In the above flowchart, the switch case begins with an expression. The expression for case1 is evaluated. If the expression is passed, then the switch will execute block1 and the operation will be terminated.

If case1 fails, then the 2nd case will be evaluated. If the expression is passed then the switch case will evaluate block3, and the operation will terminate otherwise, the expression will evaluate the next case, and so on. If no case passes the expression, then the switch statement will evaluate the default code.

How does Switch Case Statement Works in TypeScript?

The switch case takes an expression and checks for its equality. The expression can be a single integer, an enumerated value, or a string object. We use a break keyword to break the switch case. It is not mandatory to use, but if the break statement will not be there, the switch case will execute code statements that will be associated with all the cases that evaluate the expression true.

In the end, we use a default statement that is equivalent to the else of the if-else statement. It is not mandatory to use but it is used to execute a code if no case is found to be true.

Lexical Scoping

The case and default cases are like labels: they indicate possible places that control flow may jump to. Hence, they don't create lexical scopes.

In the above snippet, an error will occur Uncaught SyntaxError: Identifier 'message' has already been declared. This is because the first const message = 'hi'; is creating a conflict with the second const message = 'hello'; even when they are declared within their separate case clauses. This error is occurring as both const declarations are within the same block scope that is created by the switch body.

This error can be fixed by wrapping the conditions in a block, and let and const declarations should be enclosed in a case clause.

Output:

The above snippet will print Hi in the console as the output without any errors.

TypeScript Switch Case Statement Examples

TypeScript Switch Case Statement

Output:

In the above snippet, we have a variable, the day of the type number. The variable is declared with the value 6. The value corresponds to the day of the week. The switch statement checks the value passed and executes the block of code corresponding to that value. Hence, we get the result Today is Saturday.

Grouping Case

In grouping cases, we can group a piece of code that is being shared by multiple cases.

Output:

In the above snippet, if the month is 1, 3, 5, 7, 8, or 12 then the number of days is 31. If the month is 4, 6, 9, or 11 then the number of days is 30. If the month is 2 and the year is a leap year, it returns 29days otherwise, it returns28` days.

Switch Case with Enum

A switch case in TypeScript can be used with an enum with the following example:

Output:

In the above snippet, the fru variable is an enum type. It will be passed to the switch statement. In the switch clause, we will write the enum members for matching.

Switch Case with String

A switch case in TypeScript can be used with string with the following example:

Output:

In the above snippet, we have a string variable dir. The switch statement evaluates the dir variable value and match it with the case clauses and executes its associated statements.

Taking Advantage of Fall-Through

In the above snippet, we have a string variable dir. The switch statement evaluates the dir variable value and matches with the case clauses and executes its associated statements.

Output:

The following example given is a single operation sequential case statement where three different values perform the same operation.

Browser Compatibility of Switch Case Statement

Switch Case Browser Compatibility

Conclusion

  • The switch case in TypeScript is used when we have to move differently for different cases of an expression.
  • The switch statement takes an expression and evaluates it for all the cases and executes the code statement that is associated with the matching case.
  • In this article, we were able to see the working of the Switch Case statement and the rules that apply to the switch case.
  • We can use the default statement if all the cases fail to satisfy the expression.
  • We can use the break keyword to stop the execution of the switch case when it has processed the code statement that is associated with the matching case.
  • The switch case can be considered as an alternative to if-else statements.
  • Hope this article has provided you with the relevant information regarding Switch Statement in TypeScript.