项目代码迁移的时候遇到的,举个例子:
const getPersonInfo = (type: number) => {
switch (type) {
case 1:
const name = '张三'; // Error: Unexpected lexical declaration in case block.eslint
break;
case 2:
const name = '李四';
console.log(name); // Uncaught SyntaxError: Identifier 'name' has already been declared
break;
default:
break;
}
};
getPersonInfo(2);
可以看到,case 1 和case 2 中定义的字段,理论上应该是互不影响的,但由于作用域的提升,case1 会影响到 case 2 。
官方文档解释,let、const、function、class直接放在case或default下使用都是不正确的,必须使用花括号。
const getPersonInfo = (type: number) => {
switch (type) {
case 1: {
const name = '张三';
break;
}
case 2: {
const name = '李四';
console.log(name);
break;
}
default:
break;
}
};
getPersonInfo(2);
下面是官方文档上的示例:(不正确的写法就是去掉花括号,这里就不贴出来了)
// 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 {}
}
}