Skip to content

Commit

Permalink
fix(eslint-plugin): [prefer-optional-chain] fixer produces wrong logic (
Browse files Browse the repository at this point in the history
  • Loading branch information
sviat9440 authored and Святослав Зайцев committed Nov 2, 2022
1 parent 1eaae09 commit 1bcc7f7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
15 changes: 12 additions & 3 deletions packages/eslint-plugin/src/rules/prefer-optional-chain.ts
Expand Up @@ -221,10 +221,19 @@ export default util.createRule({

if (expressionCount > 1) {
if (previous.right.type === AST_NODE_TYPES.BinaryExpression) {
let operator = previous.right.operator;
if (
previous.right.operator === '!==' &&
previous.right.right.type === AST_NODE_TYPES.Literal &&
previous.right.right.raw === 'null'
) {
// case like foo !== null && foo.bar !== null
operator = '!=';
}
// case like foo && foo.bar !== someValue
optionallyChainedCode += ` ${
previous.right.operator
} ${sourceCode.getText(previous.right.right)}`;
optionallyChainedCode += ` ${operator} ${sourceCode.getText(
previous.right.right,
)}`;
}

context.report({
Expand Down
16 changes: 16 additions & 0 deletions packages/eslint-plugin/tests/rules/prefer-optional-chain.test.ts
Expand Up @@ -123,6 +123,22 @@ const baseCases = [
code: 'foo.bar && foo.bar?.() && foo.bar?.().baz',
output: 'foo.bar?.()?.baz',
},
{
code: 'foo !== null && foo.bar !== null',
output: 'foo?.bar != null',
},
{
code: 'foo != null && foo.bar != null',
output: 'foo?.bar != null',
},
{
code: 'foo != null && foo.bar !== null',
output: 'foo?.bar != null',
},
{
code: 'foo !== null && foo.bar != null',
output: 'foo?.bar != null',
},
].map(
c =>
({
Expand Down

0 comments on commit 1bcc7f7

Please sign in to comment.