diff --git a/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/gatherLogicalOperands.ts b/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/gatherLogicalOperands.ts index 174f8982cad8..fdb6996c612d 100644 --- a/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/gatherLogicalOperands.ts +++ b/packages/eslint-plugin/src/rules/prefer-optional-chain-utils/gatherLogicalOperands.ts @@ -248,12 +248,13 @@ export function gatherLogicalOperands( case AST_NODE_TYPES.UnaryExpression: if ( operand.operator === '!' && - isValidFalseBooleanCheckType( - operand.argument, - areMoreOperands && node.operator === '||', - parserServices, - options, - ) + (!areMoreOperands || + isValidFalseBooleanCheckType( + operand.argument, + node.operator === '||', + parserServices, + options, + )) ) { result.push({ comparedName: operand.argument, @@ -274,9 +275,10 @@ export function gatherLogicalOperands( default: if ( + !areMoreOperands || isValidFalseBooleanCheckType( operand, - areMoreOperands && node.operator === '&&', + node.operator === '&&', parserServices, options, ) diff --git a/packages/eslint-plugin/tests/rules/prefer-optional-chain/prefer-optional-chain.test.ts b/packages/eslint-plugin/tests/rules/prefer-optional-chain/prefer-optional-chain.test.ts index c05f6218b24c..a3d395e3cd37 100644 --- a/packages/eslint-plugin/tests/rules/prefer-optional-chain/prefer-optional-chain.test.ts +++ b/packages/eslint-plugin/tests/rules/prefer-optional-chain/prefer-optional-chain.test.ts @@ -1680,6 +1680,46 @@ describe('hand-crafted cases', () => { ], output: 'a?.prop;', }, + { + code: ` +declare const foo: { + bar: undefined | (() => void); +}; + +foo.bar && foo.bar(); + `, + errors: [{ messageId: 'preferOptionalChain' }], + output: ` +declare const foo: { + bar: undefined | (() => void); +}; + +foo.bar?.(); + `, + }, + { + code: ` +declare const foo: { bar: string }; + +const baz = foo && foo.bar; + `, + errors: [ + { + messageId: 'preferOptionalChain', + suggestions: [ + { + messageId: 'optionalChainSuggest', + output: ` +declare const foo: { bar: string }; + +const baz = foo?.bar; + `, + }, + ], + }, + ], + options: [{ checkString: false }], + }, ], valid: [ '!a || !b;', @@ -1917,6 +1957,10 @@ describe('hand-crafted cases', () => { !x || x.a; `, "typeof globalThis !== 'undefined' && globalThis.Array();", + ` + declare const x: void; + x && x(); + `, ], }); }); pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy