Rule Proposal: no-unscoped-case
See original GitHub issuePlease describe what the rule should do:
This rule enforces using curly braces in switch case clauses to scope them. It pairs well with the no-case-declarations rule as that rule will not warn when case clauses are wrapped in lexical blocks.
This rule will specifically enforce a style that allows use of let
/const
statements inside case statements — even with the no-case-declarations rule enabled — which allows easier, iterative, refactoring and potentially less mutation of data.
What category of rule is this? (place an “X” next to just one item)
[X] Enforces code style [ ] Warns about a potential error [ ] Suggests an alternate way of doing something [ ] Other (please specify:)
Provide 2-3 code examples that this rule will warn about:
// this will warn
switch (foo) {
case 1:
// code here
break;
}
// this will not
switch (foo) {
case 1: {
// code here
break;
}
}
Why should this rule be included in ESLint (instead of a plugin)?
It’s highly complementary to another - existing - rule as well as being a fundamental code style rule for a highly used basic language construct. Given the other rule I was actually surprised that it didn’t exist already.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:7
- Comments:8 (4 by maintainers)
Top GitHub Comments
I wonder if this would be possible to implement using the AST Selectors introduced in v3.18.0.
edit: Yup, pretty straightforward with
"no-restricted-syntax"
. This selector should match case clauses without blocks:"SwitchCase > :not(BlockStatement)"
Might be a little more useful to look for assignment within a case clause which doesn’t use a block:
"SwitchCase > ExpressionStatement > AssignmentExpression"
This is a rough draft:
switch-case-curly
This rule enforces whether you should write braces on
case:
/default:
clauses. This rule has a string option."always"
(default) requires braces."never"
disallows braces.If
"never"
is given, you can specify 2nd object option (e.g.["never", {"allowDeclarations": true}]
):allowDeclarations
allows braces if thecase:
/default:
clause has declarations to avoid confliction with no-case-declarations.Examples:
always
never
never and allowDeclarations
Hmm,
case:
/default:
clauses.