理解“无阴影变量”tslint 警告

新手上路,请多包涵

我有一个函数,它根据传入的特定规则检查顺序流中的当前阶段,并根据该值在我的 Angular 2 应用程序中分配下一个值。它看起来像这样:

 private getNextStageStep(currentDisciplineSelected) {
    const nextStageStep = '';
        if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 1') {
            const nextStageStep = 'step 2';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 2') {
            const nextStageStep = 'step 3';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 3') {
            const nextStageStep = 'step 4';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 4') {
            const nextStageStep = 'step 5';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 5') {
            const nextStageStep = 'step 6';
    }
    return nextStageStep;
}

我在这里做的是返回 nextStageStep 的值,因为这就是我将传递的值,以便正确的阶段步骤发生。

现在,我的 tslint 正在强调每个 nextStageStep 变量出现并带有警告 no shadowed variables 。如果我删除初始化为空字符串的行,则警告消失,但随后我收到错误 Cannot find nextStageStep 出现在我的返回语句中。

原始阴影变量警告有什么问题,是否有另一种方法来编写它,和/或在这种情况下我应该简单地忽略 tslint 警告吗?

原文由 Rey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 520
2 个回答

linter 抱怨是因为您多次重新定义同一个变量。从而替换包含它的闭包中的那些。

而不是重新声明它只是使用它:

 private getNextStageStep(currentDisciplineSelected) {
    let nextStageStep = '';
        if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 1') {
             nextStageStep = 'step 2';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 2') {
             nextStageStep = 'step 3';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 3') {
             nextStageStep = 'step 4';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 4') {
             nextStageStep = 'step 5';
        } else if (this.stageForDiscipline(this.currentDisciplineSelected) === 'step 5') {
             nextStageStep = 'step 6';
    }
    return nextStageStep;
}

原文由 toskv 发布,翻译遵循 CC BY-SA 3.0 许可协议

一般来说,

当局部作用域中的变量和包含作用域中的变量同名时,就会发生阴影。阴影使得无法访问包含范围内的变量,并模糊了标识符实际引用的值。

 const a = 'no shadow';
function print() {
    console.log(a);
}
print(); // logs 'no shadow'.

const a = 'no shadow';
function print() {
    const a = 'shadow'; // TSLint will complain here.
    console.log(a);
}
print(); // logs 'shadow'.

有关对此进行解释的代码示例,请参阅 本文

原文由 Junaid 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏