no-case-declarations

不允许在 case 子句中进行词法声明

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

💡 hasSuggestions

此规则报告的一些问题可通过编辑器建议手动修复

该规则不允许在 case/default 子句中使用词法声明(letconstfunctionclass)。原因是词法声明在整个 switch 块中是可见的,但它仅在分配时才被初始化,只有在达到定义它的情况下才会发生。

¥This rule disallows lexical declarations (let, const, function and class) in case/default clauses. The reason is that the lexical declaration is visible in the entire switch block but it only gets initialized when it is assigned, which will only happen if the case where it is defined is reached.

为确保词法声明仅适用于当前 case 子句,请将你的子句封装在块中。

¥To ensure that the lexical declaration only applies to the current case clause wrap your clauses in blocks.

规则详情

¥Rule Details

该规则旨在防止访问未初始化的词法绑定以及跨案例子句访问提升的函数。

¥This rule aims to prevent access to uninitialized lexical bindings as well as accessing hoisted functions across case clauses.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-case-declarations: "error"*/

switch (foo) {
    case 1:
        let x = 1;
        break;
    case 2:
        const y = 2;
        break;
    case 3:
        function f() {}
        break;
    default:
        class C {}
}

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-case-declarations: "error"*/

// Declarations outside switch-statements are valid
const a = 0;

switch (foo) {
    // The following case clauses are wrapped into blocks using brackets
    case 1: {
        let x = 1;
        break;
    }
    case 2: {
        const y = 2;
        break;
    }
    case 3: {
        function f() {}
        break;
    }
    case 4:
        // Declarations using var without brackets are valid due to function-scope hoisting
        var z = 4;
        break;
    default: {
        class C {}
    }
}

何时不使用

¥When Not To Use It

如果你依赖于失败行为并希望访问 case 块中引入的绑定。

¥If you depend on fall through behavior and want access to bindings introduced in the case block.

版本

此规则是在 ESLint v1.9.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号