TypeScript Tutorial
TypeScript Switch
switch picks a case from a value. Remember break, or execution falls through.
One value, several labels
A switch compares a value against a list of case labels. When a label matches, execution jumps there. It is a menu: the program looks at one value and picks a branch.
TypeScript can switch on numbers and on strings. C++ on this site cannot switch on a string. For ranges such as score >= 80, use if anyway. Switch wants exact matches.
A complete program
Each case ends with break; so the program leaves the switch after that branch.default runs when no label matches.
Example
const day: number = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("another day");
break;
}Change day in /typescript/try. Try 1, 3, and 9 to see a matching case and default.
case, default, break
case n:is a label.nis compared with===to the switch value.default:is the fallback. Put it last. You can omit it if every value is covered.break;jumps out of the switch. Without it, execution continues into the next case.
The parentheses after switch hold the value you test. The braces after that hold every case. Case labels themselves do not use extra parentheses.
Fall-through
If you forget break, TypeScript does not stop at the end of that case. It keeps running the statements in the following cases until it hits a break or the closing brace. That is called fall-through. It is almost always a bug.
Example
const day: number = 1;
switch (day) {
case 1:
console.log("Mon");
case 2:
console.log("Tue");
break;
default:
console.log("other");
break;
}This program prints both Mon and Tue because case 1 has no break. Add a break after every case unless you grouped empty labels on purpose.
Sharing one body
Stacking labels without statements between them is the one common, intentional fall-through. Several values run the same block.
Example
const day: number = 6;
switch (day) {
case 6:
case 7:
console.log("weekend");
break;
default:
console.log("weekday");
break;
}Switch on a string
A command word is a good fit for switch in TypeScript. Each case is a string literal. Misspell the case and it never matches — default catches that.
Example
const command: string = "save";
switch (command) {
case "open":
console.log("opening file");
break;
case "save":
console.log("saving file");
break;
case "quit":
console.log("goodbye");
break;
default:
console.log("unknown command");
break;
}switch versus if
| switch | if / else if | |
|---|---|---|
| Best for | Exact numbers, strings, or enums | Ranges and combinations |
| Strings | Yes, unlike C++ on this site | Yes |
| Easy miss | Forgotten break | Wrong order of tests |
Enums belong with switch. You will meet enum later; the shape is the same: one value, named cases, a break on each branch.
Next: while — repeating a block while a condition stays true.