no-case-declarations
注意: 此规则是
recommended
规则集的一部分。在
deno.json
中启用完整规则集{ "lint": { "tags": ["recommended"] } }
使用 Deno CLI 启用完整规则集
deno lint --tags=recommended
要求 switch case
或 default
子句中的词法声明 (let
、const
、function
和 class
) 使用括号限定作用域。
如果 case
或 default
代码块中没有括号,词法声明对整个 switch 代码块都是可见的,但只有在它们被赋值时才会被初始化,而赋值只在该 case/default 被执行时发生。这可能会导致意外错误。解决方案是确保每个 case
或 default
代码块都用括号括起来,以限制声明的作用域。
无效
switch (choice) {
// `let`, `const`, `function` and `class` are scoped the entire switch statement here
case 1:
let a = "choice 1";
break;
case 2:
const b = "choice 2";
break;
case 3:
function f() {
return "choice 3";
}
break;
default:
class C {}
}
有效
switch (choice) {
// The following `case` and `default` clauses are wrapped into blocks using brackets
case 1: {
let a = "choice 1";
break;
}
case 2: {
const b = "choice 2";
break;
}
case 3: {
function f() {
return "choice 3";
}
break;
}
default: {
class C {}
}
}