禁止 case 声明
注意:此规则是
recommended
规则集的一部分。在
deno.json
中启用完整集合{ "lint": { "rules": { "tags": ["recommended"] } } }
使用 Deno CLI 启用完整集合
deno lint --rules-tags=recommended
通过将此规则添加到
deno.json
文件中的 include
或 exclude
数组,可以将其显式地包含或排除在当前标签中的规则之外。{ "lint": { "rules": { "include": ["no-case-declarations"], "exclude": ["no-case-declarations"] } } }
要求 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 {}
}
}