switch in typescript with code examples

The switch statement in TypeScript is a control flow statement that allows you to branch your code based on a specific value or expression. It is similar to using multiple if-else statements, but is often considered to be more readable and efficient.

Here is an example of using a switch statement to determine the type of a variable:

let value: any = "hello";

switch (typeof value) {
    case "string":
        console.log("value is a string");
        break;
    case "number":
        console.log("value is a number");
        break;
    case "boolean":
        console.log("value is a boolean");
        break;
    default:
        console.log("value is of unknown type");
}

In this example, the typeof operator is used to determine the type of the variable value. Depending on the type of value, the appropriate case block is executed, and the corresponding message is logged to the console.

You can also use the switch statement to match specific values, like this:

let color: string = "green";

switch (color) {
    case "red":
        console.log("color is red");
        break;
    case "green":
        console.log("color is green");
        break;
    case "blue":
        console.log("color is blue");
        break;
    default:
        console.log("color is unknown");
}

In this example, the variable color is being checked against specific string values. If the value of color matches one of the cases, the corresponding message is logged to the console.

You can also use switch statement to match multiple values in the same case block:

let number: number = 3;

switch (number) {
    case 1:
    case 2:
    case 3:
        console.log("number is between 1 and 3");
        break;
    case 4:
    case 5:
    case 6:
        console.log("number is between 4 and 6");
        break;
    default:
        console.log("number is unknown");
}

In this example, the variable number is being checked against multiple values in the same case block. If the value of number is 1, 2 or 3, the first case block will be executed and the corresponding message will be logged to the console.

It's important to note that the break statement is used to exit the switch statement after a matching case has been found and executed. If you don't use break the code execution will continue to the next case.

In conclusion, the switch statement in TypeScript is a powerful tool for controlling the flow of your code, and can be used to create more readable and efficient code. It allows you to branch your code based on specific values or expressions and can be used to match multiple values in the same case block.

In addition to using the switch statement to control the flow of your code, there are a few other related concepts in TypeScript that you should be aware of.

One such concept is the enum type. An enum is a way of defining a set of named constants. For example, you might use an enum to represent the days of the week:

enum Day {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

You can then use the enum values in your code, like this:

let today: Day = Day.Monday;

switch (today) {
    case Day.Monday:
        console.log("Today is Monday");
        break;
    case Day.Tuesday:
        console.log("Today is Tuesday");
        break;
    // and so on
}

Another related concept is the type alias. A type alias is a way of giving a type a new name. For example, you might use a type alias to create a more meaningful name for a complex type:

type UserId = string | number;

let userId: UserId = "123";

Another related concept is the Tuple. A Tuple is an ordered list of elements. Tuples allow you to express an array where the type of a fixed number of elements is known, but need not be the same. Here is an example of a tuple:

let user: [string, number];
user = ["Alice", 25];

You can also use the destructuring assignment to assign the elements of a tuple to variables:

let user: [string, number] = ["Alice", 25];
let [name, age] = user;
console.log(name); // "Alice"
console.log(age); // 25

In addition to that, you can use the Union type which allows you to specify multiple types that a variable can be. This can be useful in cases where a variable can be of more than one type. Here's an example of a union type:

let value: string | number;
value = "hello";
console.log(value); // "hello"
value = 10;
console.log(value); // 10

In conclusion, the switch statement is a powerful tool for controlling the flow of your code in TypeScript, but it's important to also be familiar with related concepts such as enum, type alias, tuple and union types. These concepts can be used in conjunction with the switch statement to create more robust and expressive code.

Popular questions

  1. What is the purpose of the switch statement in TypeScript?
    The switch statement in TypeScript is a control flow statement that allows you to branch your code based on a specific value or expression. It is similar to using multiple if-else statements, but is often considered to be more readable and efficient.

  2. How do you use the switch statement to determine the type of a variable?
    To determine the type of a variable using the switch statement, you can use the typeof operator. For example:

let value: any = "hello";

switch (typeof value) {
    case "string":
        console.log("value is a string");
        break;
    case "number":
        console.log("value is a number");
        break;
    case "boolean":
        console.log("value is a boolean");
        break;
    default:
        console.log("value is of unknown type");
}
  1. How can you use the switch statement to match specific values?
    To use the switch statement to match specific values, you can simply use the variable or expression you want to check in the switch statement, and use the values you want to match in the case blocks. For example:
let color: string = "green";

switch (color) {
    case "red":
        console.log("color is red");
        break;
    case "green":
        console.log("color is green");
        break;
    case "blue":
        console.log("color is blue");
        break;
    default:
        console.log("color is unknown");
}
  1. What is the purpose of the break statement in the switch statement?
    The break statement is used to exit the switch statement after a matching case has been found and executed. If you don't use break, the code execution will continue to the next case.

  2. Can you give an example of using switch statement with Tuple?
    Yes, you can use the switch statement with Tuple. Here's an example:

let user: [string, number];
user = ["Alice", 25];

switch (user.length) {
    case 2:
        let [name, age] = user;
        console.log(`Name: ${name}, Age: ${age}`);
        break;
    default:
        console.log("Invalid tuple")
}

In this example, the tuple user is being checked against its length in the switch statement. If the tuple's length is 2, the tuple is destructured and the elements are assigned to variables and the corresponding message will be logged to the console.

Tag

Control-Flow.

Posts created 2498

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top