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.
Examples
Section titled “Examples”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; }}
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; } }}
Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”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.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- Biome:
noSwitchDeclarations
- Deno:
no-case-declarations
- ESLint:
no-case-declarations
- Oxlint:
eslint/no-case-declarations