Making Sense of 'No Shadowed Variable' tslint Warning

后端 未结 7 1560
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 09:58

I have a function that checks for the current stage in a sequential stream, based on a particular discipline that is passed in, and, according to that value, assigns the nex

7条回答
  •  伪装坚强ぢ
    2020-12-10 10:57

    First of all, even if you proceed with the warnings, your function "getNextStageStep()" will always return the empty value,

    • Because "const" a is block-scoped variable, and

    • It does not supports re-defining of value [Initialized value cannot be changed].

    In return block variable "nextStageStep" contains empty string value, and inner blocks "nextStageStep" variables will not mask or override the outer block's "nextStageStep" variable value.

    So whenever you return "nextStageStep", it will always return empty string.

    Inner blocks "nextStageStep" variables scope is within that if block only and here outer block "nextStageStep" variable is completely different from inner block "nextStageStep" variables.

    So if you want your code to work and if you must want to use const variables, then use multiple return statements within if blocks.

    Below is the code I checked and working fine. you can use it according to your requirement.

    function  getNextStageStep(currentDisciplineSelected) {
        const nextStageStep = '';
        if (currentDisciplineSelected === 'step 1') {
            const nextStageStep = 'step 2';
            return nextStageStep;
        } else if (currentDisciplineSelected === 'step 2') {
            const nextStageStep = 'step 3';
            return nextStageStep;
        } else if (currentDisciplineSelected === 'step 3') {
            const nextStageStep = 'step 4';
            return nextStageStep;
        } else if (currentDisciplineSelected === 'step 4') {
            const nextStageStep = 'step 5';
            return nextStageStep;
        } else if (currentDisciplineSelected === 'step 5') {
            const nextStageStep = 'step 6';
            return nextStageStep;
        }
        return nextStageStep;
    }
    console.log(getNextStageStep('step 1'));
    

    But instead writing these many return statements better to use let variable which allows you to re-define the variable value. For your problem I think @toskv solution is suitable.

提交回复
热议问题