TypeScript Switch case statement
The TypeScript switch statement combines numerous conditions into a single statement. It evaluates a Boolean, number, byte, short, int, long, enum type, string, and other expressions based on their value. Each value is represented by a single block of code in a switch statement. When a match is found, the block that corresponds to it is performed. The if-else-if ladder statement is similar to a switch statement.
Syntax
Given below is a general syntax for TypeScript Switch case statement:
switch ( expression ) {
case value1:
// statement 1
break;
case value2:
// statement 2
break;
case valueN:
// statement N
break;
default:
//
break;
}
The following items are included in the switch statement. A switch statement can contain any number of cases.
Case: Only one constant should be followed by a semicolon after the case. It is unable to take any further variables or expressions.
Break: To exit the switch statement after processing a case block, a break should be written at the conclusion of the block. If we don't write break, the execution will continue with the value that corresponds to the next case block.
Default: The switch statement ends with a default block. When there are no cases that will be matched, it executes.
In a switch statement, keep the following points in mind:
- A switch statement can contain an unlimited number of cases.
- The case values must be one-of-a-kind.
- Constant case values are required.
- At the end of each case statement, there is a break statement. The break statement is not required..
- A default block is written at the conclusion of the switch statement. It's not necessary to use the default statement.