Typescript Switch case tutorial with examples

Typescript switch class: Learn with examples. In this blog post, we are going to learn the Switch case statement with examples

Typescript Switch case

switch case is a conditional expression that checks and evaluates the expression and matched case block of code executes. This is used in place of if and else conditional expressions.

This is used to avoid multiple if and else statements to simplify the code.

Here is a switch case example

switch (conditional - expression) {
  case value_expression:
    // body statements
    // code block
    break;
  case value_expression1:
    // body statements
    // code block
    break;
  default:
    // body statements
    // code block
    break;
}

conditional-expression:

  • Conditional Expression in a switch is evaluated and finding a matching case

  • Case Block: This code inside the case block executes when Conditional Expression matches with the case block.

  • Default Block: This code block in default executes when the Conditional Expression does not match any of the case blocks.

  • Break keyword uses to break or exit from the current case block, it is optional.

  • If the break is not used, the remaining cases executed after executing matched case statement

Here is a typescript switch case Example.

Here Single case statement is used and the default is used if none of the cases are matched.

var value = "a";
switch (value) {
  case "a":
    console.log(" Letter a Checked");
    break;
  case "b":
    console.log(" Letter b Checked");
    break;
  default:
    console.log(" default letter Checked");
}

Output:

Letter a Checked

Typescript Multiple Switch cases statement Example

Multiple cases can be placed for a single code of the block.

Here is an example of this

var value = "c";
switch (value) {
  case "a":
    console.log(" Letter a Checked");
    break;
  case "b":
  case "c":
  case "d":
    console.log(" Letter b,c and d Checked");
    break;
  default:
    console.log(" default letter Checked");
    break;
}

Output:

Letter b,c, and d Checked

Typescript Switch Case Enum example

Switch expressions can contain strings and numbers. However, expressions are declared with constants.

Enum constants are defined as switch expression as well as in multiple case blocks.

Here is an example for the switch enum case example.

enum Day {
  MONDAY,
  TUESDAY,
  WEDNESDAY,
  THURSDAY,
  FRIDAY,
  SATURDAY,
  SUNDAY,
}

function isWorkingDay(day: Day) {
  switch (day) {
    case Day.SUNDAY:
      console.log("holiday");
      break;
    default:
      console.log("working day");
      break;
  }
}
const tuesday = Day.TUESDAY;
const sunday = Day.SUNDAY;
isWorkingDay(tuesday); // working day
isWorkingDay(sunday); // holiday

Output:

working day
holiday

string variable in switch and case example

String and case statements accept variables and data of string type. The value type should be primitive string, not global object String type.

Important points In the below example

  • Switch expression accepts variable of string data type
  • In each case, the value of type is a string
  • each case returns the value
  • each case has a break statement to exit from the loop
class SwitchExample {
  public isWorkingDay(weekName: string): boolean {
    switch (weekName) {
      case "saturday":
        console.log("saturday");
        return false;
        break;
      case "sunday":
        console.log("sunday");
        return false;

        break;

      default:
        console.log("working day");
        return true;

        break;
    }
  }
}

var example = new SwitchExample();
console.log(example.isWorkingDay("sunday"));
console.log(example.isWorkingDay("monday"));

output

Sunday
false
working day
true

primitive data type values in switch case

Switch cases accept primitive types of numbers as well as expressions.

Below is an example to check given number is positive or negative using a typescript switch case.

expression accepts conditional express which returns true or false, Each case block must be provided with a Boolean value.

class SwitchNumberExample {
  public isPositive(value: number): boolean {
    switch (value < 0) {
      case false:
        console.log("negative number");
        return false;
        break;
      default:
        console.log("positive number");
        return true;

        break;
    }
  }
}

var example = new SwitchNumberExample();
console.log(example.isPositive(1));
console.log(example.isPositive(-1));

Here is an output

negative number
false
positive number
true

Switch case union type with Object and interface

The below example uses the below things.

  • Created marker interfaces that have no methods
  • provided class for Animals and Lion by implementing Animal
  • Each class has a discriminator type
  • Switch case accepts union type of Dog and Lion
  • Union type expression is evaluated against string type case value
interface Animal {}

class Dog implements Animal {
  type: string = "dog";
}

class Lion implements Animal {
  type: string = "lion";
}
class SwitchClassExample {
  public getAnimal(animal: Dog | Lion) {
    switch (animal.type) {
      case "dog":
        console.log("Animal is Dog ");
        break;
      case "lion":
        console.log("Animal is Lion ");
        break;

      default:
        console.log("Other Animal types");
        break;
    }
  }
}

var example = new SwitchClassExample();
let animal = new Dog();
example.getAnimal(animal);
example.getAnimal(new Lion());

and given output:

Animal is Dog
Animal is Lion

Typescript Configuration - noFallthroughCasesInSwitch

noFallthroughCasesInSwitch value is Boolean i.e true or false.

tsconfig.json contains this configuration in a typescript application.

It returns an error for fall through switch cases.

Following is the switch case fallthrough example, where there are no break statements.

if noFallthroughCasesInSwitch=true, The below case is not allowed

switch (value) {
  case 1:
  // statements
  case 2:
  // statements 2
}

Conclusion

Learned tutorial about Typescript Switch case syntax and multiple expressions enum break examples. And also fixed the typescript configuration noFallthroughCasesInSwitch