Skip to content

caseDeclarations

Reports lexical declarations in case clauses without wrapping them in blocks.

✅ This rule is included in the ts untyped preset.

Lexical declarations (let, const, function, class) in case and default clauses are scoped to the entire switch statement block, not just to the individual clause where they appear. This can lead to unexpected behavior when multiple clauses attempt to declare variables with the same name, resulting in syntax errors or unintended variable shadowing. Wrapping the contents of case clauses in curly braces creates a proper block scope, preventing these issues.

function processValue(value: number): string {
switch (value) {
case 1:
let result = "one";
return result;
case 2:
let result = "two";
return result;
default:
let result = "other";
return result;
}
}
function handleType(type: string): void {
switch (type) {
case "user":
const data = fetchUserData();
processData(data);
break;
case "admin":
const data = fetchAdminData();
processData(data);
break;
}
}

This rule is not configurable.

If you are certain that you will never have variable name conflicts between case clauses and you understand the scoping implications, you might choose to disable this rule. However, using block scopes in case clauses is a best practice that prevents potential bugs and makes the code’s intent clearer.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.