@@ -363,15 +363,18 @@ export default createRule<Options, MessageId>({
363
363
'===' ,
364
364
'!=' ,
365
365
'!==' ,
366
- ] ) ;
367
- function checkIfBinaryExpressionIsNecessaryConditional (
368
- node : TSESTree . BinaryExpression ,
366
+ ] as const ) ;
367
+ type BoolOperator = Parameters < typeof BOOL_OPERATORS . has > [ 0 ] ;
368
+ const isBoolOperator = ( operator : string ) : operator is BoolOperator =>
369
+ ( BOOL_OPERATORS as Set < string > ) . has ( operator ) ;
370
+ function checkIfBoolExpressionIsNecessaryConditional (
371
+ node : TSESTree . Node ,
372
+ left : TSESTree . Node ,
373
+ right : TSESTree . Node ,
374
+ operator : BoolOperator ,
369
375
) : void {
370
- if ( ! BOOL_OPERATORS . has ( node . operator ) ) {
371
- return ;
372
- }
373
- const leftType = getConstrainedTypeAtLocation ( services , node . left ) ;
374
- const rightType = getConstrainedTypeAtLocation ( services , node . right ) ;
376
+ const leftType = getConstrainedTypeAtLocation ( services , left ) ;
377
+ const rightType = getConstrainedTypeAtLocation ( services , right ) ;
375
378
if ( isLiteral ( leftType ) && isLiteral ( rightType ) ) {
376
379
context . report ( { node, messageId : 'literalBooleanExpression' } ) ;
377
380
return ;
@@ -390,7 +393,7 @@ export default createRule<Options, MessageId>({
390
393
ts . TypeFlags . TypeVariable ;
391
394
392
395
// Allow loose comparison to nullish values.
393
- if ( node . operator === '==' || node . operator === '!=' ) {
396
+ if ( operator === '==' || operator === '!=' ) {
394
397
flag |= NULL | UNDEFINED | VOID ;
395
398
}
396
399
@@ -719,13 +722,34 @@ export default createRule<Options, MessageId>({
719
722
720
723
return {
721
724
AssignmentExpression : checkAssignmentExpression ,
722
- BinaryExpression : checkIfBinaryExpressionIsNecessaryConditional ,
725
+ BinaryExpression ( node ) : void {
726
+ const { operator } = node ;
727
+ if ( isBoolOperator ( operator ) ) {
728
+ checkIfBoolExpressionIsNecessaryConditional (
729
+ node ,
730
+ node . left ,
731
+ node . right ,
732
+ operator ,
733
+ ) ;
734
+ }
735
+ } ,
723
736
CallExpression : checkCallExpression ,
724
737
ConditionalExpression : ( node ) : void => checkNode ( node . test ) ,
725
738
DoWhileStatement : checkIfLoopIsNecessaryConditional ,
726
739
ForStatement : checkIfLoopIsNecessaryConditional ,
727
740
IfStatement : ( node ) : void => checkNode ( node . test ) ,
728
741
LogicalExpression : checkLogicalExpressionForUnnecessaryConditionals ,
742
+ SwitchCase ( { test, parent } ) : void {
743
+ // only check `case ...:`, not `default:`
744
+ if ( test ) {
745
+ checkIfBoolExpressionIsNecessaryConditional (
746
+ test ,
747
+ parent . discriminant ,
748
+ test ,
749
+ '===' ,
750
+ ) ;
751
+ }
752
+ } ,
729
753
WhileStatement : checkIfLoopIsNecessaryConditional ,
730
754
'MemberExpression[optional = true]' : checkOptionalMemberExpression ,
731
755
'CallExpression[optional = true]' : checkOptionalCallExpression ,
0 commit comments