- Learning TypeScript 2.x
- Remo H. Jansen
- 292字
- 2025-04-04 17:02:04
The multiple-selection structure (switch)
The switch statement evaluates an expression, matches the expression's value to a case clause, and executes statements associated with that case. Switch statements and enumerations are often used together to improve the readability of the code.
In the following example, we declare a function that takes an enumeration named AlertLevel.
Inside the function, we will generate an array of strings to store email addresses and execute a switch structure. Each of the options of the enumeration is a case in the switch structure:
enum AlertLevel{
info, warning, error } function getAlertSubscribers(level: AlertLevel){ let emails = new Array<string>(); switch(level){ case AlertLevel.info: emails.push("cst@domain.com"); break; case AlertLevel.warning: emails.push("development@domain.com"); emails.push("sysadmin@domain.com"); break; case AlertLevel.error: emails.push("development@domain.com"); emails.push("sysadmin@domain.com"); emails.push("management@domain.com"); break; default: throw new Error("Invalid argument!"); } return emails; } getAlertSubscribers(AlertLevel.info); // ["cst@domain.com"] getAlertSubscribers(AlertLevel.warning); //
["development@domain.com", "sysadmin@domain.com"]
The value of the level variable is tested against all the cases in the switch. If the variable matches one of the cases, the statement associated with that case is executed. Once the case statement has been executed, the variable is tested against the next case.
Once the execution of the statement associated with a matching case is finalized, the next case will be evaluated. If the break keyword is present, the program will not continue the execution of the following case statement.
If no matching case clause is found, the program looks for the optional default clause, and if found, it transfers control to that clause and executes the associated statements.
If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not have to be so.