noFallthroughCasesInSwitch

To further check logic errors in our code, we can use the noFallthroughCasesInSwitch compile option to check Switch statements. Consider the following code:

enum SwitchEnum { 
    ONE, 
    TWO 
} 
 
function testEnumSwitch(value: SwitchEnum) : string { 
    let returnValue = ""; 
    switch(value) { 
        case SwitchEnum.ONE: 
            returnValue = "One"; 
        case SwitchEnum.TWO: 
            returnValue = "Two"; 
    } 
    return returnValue; 
} 

Here, we have defined an enum named SwitchEnum that has two values, ONE and TWO. We then define a function named testEnumSwitch that returns a string value based on the input parameter name value, which is of type SwitchEnum. Within this function, we define a variable named returnValue, and set it to an empty string. We then have a switch statement that assigns the value of the returnValue variable to either "One" or "Two", based on the enum passed in. This code will generate the following error:

error TS7029: Fallthrough case in switch. 

This error is correctly identifying a logic error within our switch statement. Note that if the input argument value is SwitchEnum.ONE, we are assigning the value of the returnValue variable to "One". Unfortunately, the logic automatically falls through to the second case statement, where the returnValue variable is set to "Two". This means that no matter whether the value argument that is passed in is SwitchEnum.ONE, or SwitchEnum.TWO, the return value will always be "Two".

This code needs to be corrected as follows:

function testEnumSwitch(value: SwitchEnum) : string { 
    let returnValue = ""; 
    switch(value) { 
        case SwitchEnum.ONE: 
            returnValue = "One"; 
            break; 
        case SwitchEnum.TWO: 
            returnValue = "Two"; 
    } 
    return returnValue; 
} 

Here, the subtle difference that fixes the compile error is the inclusion of the break statement in the case SwitchEnum.ONE logic. This break statement will break the switch statement, and avoid the code falling through to the second case statement.

So what we have seen then, is the compiler correctly identifying where we have glaring errors in our switch statements, and where logic will fall through from one switch case to another. While these errors may seem easy to spot in such simple code samples, they can quickly become lost in larger code bases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.68.14