Switch in TypeScript
Here’s the translated content in TypeScript, maintaining the original structure and explanations:
Switch statements express conditionals across many branches.
Here’s a basic switch.
let i = 2;
console.log("Write ", i, " as ");
switch (i) {
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
case 3:
console.log("three");
break;
}You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.
const now = new Date();
switch (now.getDay()) {
case 6: // Saturday
case 0: // Sunday
console.log("It's the weekend");
break;
default:
console.log("It's a weekday");
}switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.
const t = new Date();
switch (true) {
case t.getHours() < 12:
console.log("It's before noon");
break;
default:
console.log("It's after noon");
}A type switch compares types instead of values. You can use this to discover the type of a variable. In this example, the variable t will have the type corresponding to its clause.
function whatAmI(i: any) {
switch (typeof i) {
case "boolean":
console.log("I'm a bool");
break;
case "number":
console.log("I'm an int");
break;
default:
console.log(`Don't know type ${typeof i}`);
}
}
whatAmI(true);
whatAmI(1);
whatAmI("hey");To run the program, put the code in a file and use ts-node or compile it with tsc and use node to execute it.
$ ts-node example.ts
Write 2 as
two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string