Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [prefer-optional-chain] fixer produces wrong logic #5919

Merged
merged 10 commits into from Jan 26, 2023
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'
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
) {
// 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',
},
sviat9440 marked this conversation as resolved.
Show resolved Hide resolved
].map(
c =>
({
Expand Down