How to use switch statement in TypeScript

5 Answers

0 votes
let day : number = 3;

switch (day) {
    case 1:
        console.log("Sunday");
        break;
    case 2:
        console.log("Monday");
        break;
    case 3:
        console.log("Tuesday");
        break;
    case 4:
        console.log("Wednesday");
        break;
    case 5:
        console.log("Thursday");
        break;
    case 6:
        console.log("Friday");
        break;
    case 7:
        console.log("Saturday");
        break;
    default:
        console.log("Not exists");
        break;
}
  
   
   
   
/*
   
run:
   
"Tuesday" 
  
*/

 

 



answered Oct 24, 2021 by avibootz
0 votes
let x = 13, y = 5;

switch (x - y) {
    case 0:
        console.log("= 0");
        break;
    case 8:
        console.log("= 8");
        break;
    case 4:
        console.log("= 4");
        break;
}
  
   

   
/*
   
run:
   
"= 8" 
  
*/

 



answered Oct 24, 2021 by avibootz
0 votes
function getText(lang: any) { 
    let text = "";
   
    switch(lang) {
        case "cpp":
            text = "cpp";
            break;
        case "typescript":
            text = "typescript";
            break;
        case "php":
            text = "php";
            break;
        default:
            text = "default";
    }
    return text;
}
    
console.log(getText("typescript")); 
   
   
   
    
/*
run:
   
"typescript"
   
*/

 



answered May 21, 2023 by avibootz
0 votes
function get_value(n: number) { 
   let text : string;
     
   switch (n) {
      case 1:
      case 2:
      case 3:
            text = "n = 1 , 2 or 3";
            break;
      case 4:
      case 5:
            text = "n = 4 or 5";
            break;
      case 9:
      case 13:
            text = "n = 9 or 13";
            break;
      default:
            text = "default";
   }
   return text;
}
   
console.log(get_value(9)); 
  
  
  
   
/*
run:
  
"n = 9 or 13" 
  
*/

 



answered May 21, 2023 by avibootz
0 votes
const n: number = 2;
 
switch (n) {
    case 0:
        console.log(0);
    case 1:
        console.log(1);
    case 2:
        console.log(2);
    case 3:
        console.log(3);
    case 4:
        console.log(4);
    case 5:
        console.log(5);
        break;
    case 6:
        console.log(6);
        break;        
  default:
        console.log("default");
}
 
 
   
   
   
    
/*
run:
   
2 
3 
4 
5 
   
*/

 



answered May 21, 2023 by avibootz

Related questions

1 answer 134 views
1 answer 100 views
1 answer 87 views
1 answer 101 views
1 answer 90 views
1 answer 87 views
...