Home > Enterprise >  typescript switch not working with interger input
typescript switch not working with interger input

Time:11-18

i have a switch like this

switch (value){
      case 1 : {
        res = value "Hirukami Murakmi"
        break;
      }
      case 2 : {
        res = value "Josephine"
        break;
      }
      default: {
        res = value "Mikey n Blaky"
        break;
      }

it is not working, it always show default value. i add value just to know the value, and it is correctly define

but if else is working well

 if (value == 1) { res = "Hirukami Murakmi"}
    else if (value == 2) { res = "Josephine"}
    else { res = "Mikey n Blaky"}

i don't know what is wrong with my switch

CodePudding user response:

When doing with if/else statements you are writing double equals (value == 1).

The switch also compares types, like if you do with triple equals. Therefore it might be that the value is and it won't land in the cases, always at default one.

You should cast value as a number or do the cases as strings.

CodePudding user response:

Maybe the value is not a number but it is a string then you can do the next:

    switch (value){
      case "1": {
        res = value "Hirukami Murakmi"
        break;
      }
      case "2": {
        res = value "Josephine"
        break;
      }
      default: {
        res = value "Mikey n Blaky"
        break;
      }

Or you can do next:

switch (true){
  case value == 1 : {
    res = value "Hirukami Murakmi"
    break;
  }
  case value == 2 : {
    res = value "Josephine"
    break;
  }
  default: {
    res = value "Mikey n Blaky"
    break;
  }

}

  • Related