Open In App

How to Use a Typescript Switch on Multiple Inputs ?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, switch statements offer a succinct method for managing several conditions depending on the value of an expression. However, the conventional switch syntax may not seem sufficient when handling numerous inputs.

Combining Inputs into a Single Value

Combining several inputs into a single value is one technique to handle them. When inputs may be expressed as flags or when each input contributes to a different bit of the total value, this method is especially helpful.

Example: The below code will explain how you can combine multiple inputs and use them with switch statements.

Javascript
enum Inputs {
    Input1 = 1,
    Input2 = 2,
    Input3 = 4,
}

function handleCombinedInput
    (combinedInput: Inputs[]): void {
    for (const input of combinedInput) {
        switch (input) {
            case Inputs.Input1:
                console.log("Handling Input1");
                break;
            case Inputs.Input2:
                console.log("Handling Input2");
                break;
            case Inputs.Input3:
                console.log("Handling Input3");
                break;
            default:
                console.log("Handling default case");
        }
    }
}

let combinedInput: Inputs[] =
    [Inputs.Input1, Inputs.Input2, Inputs.Input3];
handleCombinedInput(combinedInput);

Output:

Handling Input1
Handling Input2
Handling Input3

Using Nested Switch Statements

Another approach to handling multiple inputs is by using nested switch statements. This method is suitable when the inputs are independent of each other and need to be evaluated separately.

Example: The below code uses nested switch statements to handle multiple inputs within them.

Javascript
function handleInputCombination
    (input1: number, input2: number, input3: number):
    void {
    switch (input1) {
        case 1:
            switch (input2) {
                case 2:
                    switch (input3) {
                        case 3:
                            console.log
                                ("Handling input combination 1, 2, 3");
                            break;
                        default:
                            console.log
                                ("Handling default case for input3");
                            break;
                    }
                    break;
                default:
                    console.log
                        ("Handling default case for input2");
                    break;
            }
            break;
        default:
            console.log("Handling default case for input1");
            break;
    }
}

handleInputCombination(1, 2, 3);

Output:

Handling input combination 1, 2, 3

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads