TypeScript Switch Case Statement

This acts like a multiple if / else if / else chain. Checks an value against a list of cases, and executes the first case that is true. If no matching case found, it executes the default case. The break(optional) statements with case indicate to the interpreter to end the particular case.

Syntax

switch (expression) {
  case case1:
    statements1
    [break;]
  case case2:
    statements2
    [break;]
  case case3:
    statements3
    [break;]
  default:
    default statements
    [break;]
}

TypeScript Switch Case Example 1

CheckBookPrice(book:string) : string
{ 
   switch (book) {
	  case "English":
		msg = "English book price is $12.";
		break;
	  case "Math":
		msg = "Math book price is $22.";
		break;
	  case "Commerce":
		msg = "Commerce book price is $12.";
		break;
	  case "History":
		msg = "History book price is $125.";
		break;
	  case "Physics":
		msg = "Physics book price is $12.99.";
		break;
	  default:
		msg = "Sorry, book out of stock";
	}
	return msg;
}
								
Try it Yourself

If you forget a break statement, which is optional than script will run from the case where condition is met, and will run the case after that regardless if condition was met.

TypeScript Switch Case Example 2

CheckDesignation(salary:string) : string
{ 
	switch (salary)
	{
	  case '10000': 
		msg = "Assistant";
		break;
	  case '20000': 
		msg = "Assistant Manager";
		break;
	  case '30000': 
		msg = "Relationship Manager";
		break;
	  case '40000': 
	  case '50000': 
		msg = "Manager";
		break;
	  default:  
		msg = "Unknown post";
	}
return msg;
}
								
Try it Yourself