TypeScript switch statement evaluates an expression, and based on its value (not necessarily boolean, it could be number, string, etc.), one of the many cases is matched against. When there is a match, the corresponding block is executed.
TypeScript Switch
There are much more points to be noted while using switch conditional statement, which we shall look into, right after syntax section.
Syntax
Following is the syntax of TypeScript switch statement:
switch (expression){
case constant1 : {
// this is first case block
break
}
case constant2 : {
// this is second case block
// and there can be any number of cases
break
}
default : {
// when no case is matched, this block executes
break
}
}
- There could be any number of cases inside switch statement.
- case has to be followed by only constants and then a semi-colon. It cannot be another expression or variable.
- break has to follow at the end of block to come out of switch statement after executing a case block. Else, the execution continues with with matching the value to the constants of subsequent case blocks.
- When no case is matched, the default block written at the end of switch is executed.
Example – TypeScript Switch
Following is a simple typescript switch statement example, where the expression is addition of two variables, and the cases has some of the possible values. Only the case block that matches its value with the expression gets executed.
example.ts
var a:number = 1
var b:number = 3
switch (a+b){
case 1 : {
console.log("a+b is 1.")
break
}
case 3 : {
console.log("a+b is 3.")
break
}
case 4 : {
console.log("a+b is 4.")
break
}
case 5 : {
console.log("a+b is 5.")
break
}
default : {
console.log("a+b is 5.")
break
}
}
When the above typescript file is compiled using tsc example.ts
, following JavaScript file is generated.
example.js
var a = 1;
var b = 3;
switch (a + b) {
case 1: {
console.log("a+b is 1.");
break;
}
case 3: {
console.log("a+b is 3.");
break;
}
case 4: {
console.log("a+b is 4.");
break;
}
case 5: {
console.log("a+b is 5.");
break;
}
default: {
console.log("a+b is 5.");
break;
}
}
Output
a+b is 4.
Concluding this TypeScript Tutorial, we have learnt TypeScript switch conditional statement, its syntax and usage with the help of an example.