TypeScript Switch Case

A switch case statement is used when we have to execute between different blocks of code based on a condition. It replaces the need for multiple if…elseif conditions and provides more clean code.

Switch evaluates an expression and then matches it with different case clauses. If any value matches the case clause, then it executes the associated code block statement; otherwise, it executes the default case statement.

Switch Case Syntax

switch (expression) {
    case n1: //code block statement1;
        break;
    case n2: //code block statement2;
        break;
    case n3: //code block statement3;
        break;
    default:
        //default block statement;
}

The condition specified in the expression is evaluated and matches with the case statements. For example, if the expression value evaluates to n1, then only code block statement 1 is executed. ‘break’ is always required so that it will not execute other block statements.

‘default’ case will only execute when expression does not match with any other case clauses. ‘default’ case can come in any order but it always evaluate in the last after all cases are evaluated.

Switch case can be executed with multiple data types. Below are the examples:

Switch Number Variable Example

var month: number = 4;
var monthName: string;

switch (month) {
    case 1: monthName = 'January';
        break;
    case 2: monthName = 'February';
        break;
    case 3: monthName = 'March';
        break;
    case 4: monthName = 'April';
        break;
    case 5: monthName = 'May';
        break;
    case 6: monthName = 'June';
        break;
    case 7: monthName = 'July';
        break;
    case 8: monthName = 'August';
        break;
    case 9: monthName = 'September';
        break;
    case 10: monthName = 'October';
        break;
    case 11: monthName = 'November';
        break;
    case 12: monthName = 'December';
        break;
    default:
        monthName = 'Undefined';
}
console.log('Month Name: ' + monthName);

In above example, we have declared a month number variable and a monthName string variable. We have used month number variable as Switch case expression. ‘month’ variable value is matched with case clauses values and which case clause value is matched, then it’s associated code statement will execute.

For example, month variable value is 4 then case clause with value 4, ‘ monthName = ‘April;’, is executed and rest case clauses will be discarded.

String Case Variable Example

var direction: string = "north";

switch (direction) {
    case 'north': console.log('Go to North Direction');
        break;
    case 'east': console.log('Go to Eest Direction');
        break;
    case 'south': console.log('Go to Soutch Direction');
        break;
    case 'west': console.log('Go to West Direction')
        break;
    default:
        console.log('invalid direction');
}

In above example, we have a string variable direction. Switch statement evaluates direction variable value and match with case clauses and execute its associated statements.

In string cases, a variable can come in any cases like capital case, upper case or lower case. In above example, if direction value comes in upper case “NORTH” then case ‘north’ will not match. To remove this problem we should use toLowerCase function with switch statement. ‘toLowerCase’ function converts variable value to lowercase then switch statement match with case clause. Below is the example:

var direction: string = "North";

switch (direction.toLowerCase()) {
    case 'north': console.log('Go to North Direction');
        break;
    case 'east': console.log('Go to Eest Direction');
        break;
    case 'south': console.log('Go to Soutch Direction');
        break;
    case 'west': console.log('Go to West Direction')
        break;
    default:
        console.log('invalid direction');
}

Multiple Switch Cases Example

We can write multiple case clauses associated with single code block statement. This switch is used when we have to execute same code block for multiple case clauses. Below is the example:

var marks: number = 8;

switch (marks) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
        console.log('Low numbers');
        break;
    case 5:
    case 6:
    case 7:
    case 8:
        console.log('Middle numbers');
        break;
    case 9:
    case 10:
        console.log('Good numbers');
        break;
    default:
        console.log('invalid numbers');
}

In above example, if marks is between 0 to 4 then first code block ‘Low numbers’ will execute, and if marks between 5 to 8 second code block ‘Middle numbers’ will execute.

There is one other trick to simplify the above switch statement.

var marks: number = 9;

switch (true) {
    case (marks >= 0 && marks <= 4):
        console.log('Low numbers');
        break;
    case (marks >= 5 && marks <= 8):
        console.log('Middle numbers');
        break;
    case (marks >= 9 && marks <= 10):
        console.log('Good numbers');
        break;
    default:
        console.log('invalid numbers');
}

In this example, we will always pass true in the switch expression, then which case clause is evaluated to true, then associated code block is executed.

TypeScript Switch Enum Example

A switch case can be use with Enum in TypeScript like shown below:

enum Direction {
    North,
    East,
    South,
    West
};

var dir: Direction = Direction.South;

function getDirection() {
    switch (dir) {
        case Direction.North: console.log('North Direction');
            break;
        case Direction.East: console.log('East Direction');
            break;
        case Direction.South: console.log('South Direction');
            break;
        case Direction.West: console.log('West Direction');
            break;

    }
}

getDirection(); //print South Direction in console

In above switch statement, dir variable is an enum type. This variable is passed to switch statement. In switch clauses, we write enum members for matching.

Instance Of Switch

‘Instance of’ is used to check whether an object is an instance of particular class or not. By default, instance of is not supported by TypeScript in switch statement. Below is the example how we can use instance of using a trick.

interface IMember {
}

class NormalMember implements IMember {
}

class SilverMember implements IMember {
}

class GoldMember implements IMember {
}

var member: IMember = new GoldMember();

function getInstanceOf(mem: IMember): number {
    if (mem instanceof NormalMember)
        return 1;
    else if (mem instanceof SilverMember)
        return 2;
    else if (mem instanceof GoldMember)
        return 3;
    return 0;
}

switch (getInstanceOf(member)) {
    case 1:
        console.log('Normal Member');
        break;
    case 2:
        console.log('Silver Member');
        break;
    case 3:
        console.log('Gold Member');
        break;
    case 4:
        console.log('Invalid Member');
}

We have created three class NormalMember, SilverMember, and GoldMember. All three classes implements the IMember interface. We declare a variable member and assigned a new instance of GoldMember class.

We write a reusable function getInstanceOf which return 1, 2 and 3 for NormalMember, SilverMember, and GoldMember respectively. In switch statement, we call getInstanceOf function and match return value of function with case clause.

typeOf / Union Type Switch Statement

typeOf and Union Type is also not supported by TypeScript in switch statement. To remove this problem we have to write a reusable function which actually check typeof and return number based on datatypes. Below is the example:

var var1 = 'hello';

var var2: number | string | boolean;
var2= true;

function getTypeOf(v) {
    if (typeof (v) === 'number')
        return 1;
    else if (typeof (v) === 'string')
        return 2;
    else if (typeof (v) === 'boolean')
        return 3;
    return 0;
}

switch (getTypeOf(var1)) {
    case 1:
        console.log('typeof number');
        break;
    case 2:
        console.log('typeof string');
        break;
    case 3:
        console.log('typeof boolean');
    default:
        console.log('invalid type');
        break;
}
//print typeof string

switch (getTypeOf(var2)) {
    case 1:
        console.log('number type');
        break;
    case 2:
        console.log('string type');
        break;
    case 3:
        console.log('boolean type');
        break;
    default:
        console.log('invalid type');
        break;
}

//print boolean type

Summary

A switch case statement is used when we have to choose between different code block statements based on expressions with code readability in mind. The switch statement removes the need to multiple if..elseif conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.