TypeScript Switch Statement
The TypeScript switch statement executes one statement from multiple conditions. It evaluates an expression based on its value that could be Boolean, number, byte, short, int, long, enum type, string, etc. A switch statement has one block of code corresponding to each value. When the match is found, the corresponding block will be executed. A switch statement works like the if-else-if ladder statement.
The following points must be remembered in a switch statement:
The switch statement contains the following things. There can be any number of cases inside a switch statement.
Case: The case should be followed by only one constant and then a semicolon. It cannot accept another variable or expression.
Break: The break should be written at the end of the block to come out from the switch statement after executing a case block. If we do not write break, the execution continues with the matching value to the subsequent case block.
Default: The default block should be written at the end of the switch statement. It executes when there are no case will be matched.
Switch case with String
In this example, we have a string variable grade. The switch statement evaluates grade variable value and match with case clauses and then execute its associated statements.
Switch Case with Enum
In TypeScript, we can use the switch case with Enum in the following ways.
TypeScript Switch Statement is fall-through.
The TypeScript switch statement is fall-through. It means if a break statement is not present, then it executes all statements after the first match case.