Typescript switch statement
Created By: chatGPT
In TypeScript, a switch statement is used to execute different parts of code based on the value of a variable or expression. It is an alternative to multiple if-else statements when you are checking against a single expression for multiple conditions. Here’s how you can use the switch statement effectively.
const fruit = 'apple';
switch (fruit) {
case 'apple':
console.log('This is an apple.');
break;
case 'banana':
console.log('This is a banana.');
break;
case 'orange':
console.log('This is an orange.');
break;
default:
console.log('Unknown fruit.');
}
Each case inside the switch statement checks if the expression matches a specific value. If a match is found, the corresponding block of code executes. The break statement is crucial as it prevents the code from falling through to subsequent cases. If none of the cases match, the default case is executed, if it exists.
const number = 2;
switch (number) {
case 1:
console.log('One');
break;
case 2:
console.log('Two');
break;
case 3:
console.log('Three');
break;
default:
console.log('Not One, Two, or Three');
}
You can also use expressions directly in cases. For TypeScript, it's essential to note that the cases are strictly evaluated using the === operator. This means not only values but also types must match for a case to execute.
const value = '1';
switch (value) {
case 1:
console.log('This will not execute because the types differ.');
break;
case '1':
console.log('This will execute because value is a string.');
break;
default:
console.log('Default case');
}
When using a switch statement, remember to include break statements after each case unless you intend to allow fall-through behavior. Fall-through occurs when no break is found, leading to the execution of subsequent cases until a break is encountered or the switch ends.
const day = 3;
switch (day) {
case 1:
console.log('Monday');
case 2:
console.log('Tuesday');
case 3:
console.log('Wednesday');
break;
case 4:
console.log('Thursday');
break;
default:
console.log('Another day');
}