Skip to content

caseDeclarations

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

✅ This rule is included in the ts untyped presets.

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
function processValue(value: number): string
processValue
(
value: number
value
: number): string {
switch (
value: number
value
) {
case 1:
let
let result: string
result
= "one";
return
let result: string
result
;
case 2:
let
let result: string
result
= "two";
return
let result: string
result
;
default:
let
let result: string
result
= "other";
return
let result: string
result
;
}
}
function
function handleType(type: string): void
handleType
(
type: string
type
: string): void {
switch (
type: string
type
) {
case "user":
const
const data: any
data
=
const fetchUserData: any
fetchUserData
();
const processData: any
processData
(
const data: any
data
);
break;
case "admin":
const
const data: any
data
=
const fetchAdminData: any
fetchAdminData
();
const processData: any
processData
(
const data: any
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 ❤️‍🔥 around the world by the Flint team and contributors.