/  Technology   /  How can write switch case for value of a prop of a subject in a TypeScript file ?
How can write switch case for value of a prop of a subject in a TypeScript file ?

How can write switch case for value of a prop of a subject in a TypeScript file ?

 

The TypeScript(TS) switch statement is provide to check for multiple conditions values and executes sets of statements for each of those condition values. Switch statement has one block of code corresponding to each condition value and can have any number of such blocks, when the match to a value is found, the corresponding block of code is executed.

Syntax:

switch(expression) { 
case constant-expression1: { 
//statements; 
break; 
} 
case constant_expression2: { 
//statements; 
break; 
} 
default: { 
//statements; 
break; 
} 
}

⦁ The switch statement can include constant(const) or variable(var) expression which can return a value of any data type.
⦁ It can be any number of case statements within a switch statement. The case can include a constant(cont) or an expression.
⦁ We must use break keyword at the end of each case block to stop the execution(switch statement) of the case block.
⦁ The return type of the switch expression and case expression must be match.
⦁ The default block is optional.

let x = 10, y = 5;

switch (x-y) {
case 0:
console.log("Result: 0");
break;
case 5:
console.log("Result: 5");
break;
case 10:
console.log("Result: 10");
break;
}

 

Leave a comment