Skip to content

fix(eslint-plugin): [prefer-nullish-coalescing] mal-fixes nested conditional expression #11098

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

mdm317
Copy link
Contributor

@mdm317 mdm317 commented Apr 24, 2025

PR Checklist

Overview

When running the Fix, add parentheses to conditional expressions that are missing them

@typescript-eslint
Copy link
Contributor

Thanks for the PR, @mdm317!

typescript-eslint is a 100% community driven project, and we are incredibly grateful that you are contributing to that community.

The core maintainers work on this in their personal time, so please understand that it may not be possible for them to review your work immediately.

Thanks again!


🙏 Please, if you or your company is finding typescript-eslint valuable, help us sustain the project by sponsoring it transparently on https://opencollective.com/typescript-eslint.

Copy link

netlify bot commented Apr 24, 2025

Deploy Preview for typescript-eslint ready!

Name Link
🔨 Latest commit 07a6d71
🔍 Latest deploy log https://app.netlify.com/sites/typescript-eslint/deploys/680fa2e513e43d0008e7362e
😎 Deploy Preview https://deploy-preview-11098--typescript-eslint.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 75 (🔴 down 16 from production)
Accessibility: 100 (no change from production)
Best Practices: 100 (no change from production)
SEO: 98 (no change from production)
PWA: 80 (no change from production)
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

nx-cloud bot commented Apr 24, 2025

View your CI Pipeline Execution ↗ for commit 07a6d71.

Command Status Duration Result
nx run eslint-plugin:test -- --coverage ✅ Succeeded 6m 22s View ↗
nx test eslint-plugin ✅ Succeeded 6m 6s View ↗
nx test eslint-plugin --coverage=false ✅ Succeeded 5m 8s View ↗
nx test ast-spec ✅ Succeeded 2s View ↗
nx run types:build ✅ Succeeded 1s View ↗
nx typecheck ast-spec ✅ Succeeded 2s View ↗
nx test eslint-plugin-internal ✅ Succeeded 1s View ↗
nx test rule-tester ✅ Succeeded 1s View ↗
Additional runs (26) ✅ Succeeded ... View ↗

☁️ Nx Cloud last updated this comment at 2025-04-28 16:01:11 UTC

Copy link

codecov bot commented Apr 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.84%. Comparing base (5c2f474) to head (07a6d71).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #11098   +/-   ##
=======================================
  Coverage   90.83%   90.84%           
=======================================
  Files         497      497           
  Lines       50259    50273   +14     
  Branches     8291     8294    +3     
=======================================
+ Hits        45652    45668   +16     
+ Misses       4592     4590    -2     
  Partials       15       15           
Flag Coverage Δ
unittest 90.84% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...lint-plugin/src/rules/prefer-nullish-coalescing.ts 98.26% <100.00%> (+0.03%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mdm317 mdm317 marked this pull request as ready for review April 24, 2025 14:30
@OlivierZal
Copy link
Contributor

Looks good!

Copy link
Member

@kirkwaiblinger kirkwaiblinger left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like it will solve the specific bug case but just have a question about being generic and/or reusing code. Thanks for sending!

@@ -932,3 +934,17 @@ function formatComments(
)
.join('');
}

function getTextWithEnsuredParentheses(
Copy link
Member

@kirkwaiblinger kirkwaiblinger Apr 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we can leverage existing infrastructure around parenthesization/wrapping rather than hard-code a special case for a ? b : c... is there a specific reason to do that? I worry we might miss parens on other expressions that might need it?

FWIW I had success passing all the test cases with the following...

          context.report({
            node,
            messageId: 'preferNullishOverTernary',
            // TODO: also account for = in the ternary clause
            data: { equals: '' },
            suggest: [
              {
                messageId: 'suggestNullish',
                data: { equals: '' },
                fix(fixer: TSESLint.RuleFixer): TSESLint.RuleFix {
                  return fixer.replaceText(
                    node,
                    `${getTextWithParentheses(
                      context.sourceCode,
                      nullishCoalescingParams.nullishCoalescingLeftNode,
                    )} ?? ${(() => {
                      const branch = getBranchNodes(
                        node,
                        operator,
                      ).nullishBranch;
                      if (isParenthesized(branch, context.sourceCode)) {
                        return getTextWithParentheses(
                          context.sourceCode,
                          branch,
                        );
                      }
                      return getWrappedCode(
                        getTextWithParentheses(context.sourceCode, branch),
                        getOperatorPrecedenceForNode(branch),
                        OperatorPrecedence.Coalesce,
                      );
                    })()}`,
                  );
                },
              },
            ],
          });

Curious what you think!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It definitely seems much better to use the existing infrastructure rather than hard-coding it!
I've updated the code to use your approach.
Thanks for pointing it out!

@kirkwaiblinger kirkwaiblinger added the awaiting response Issues waiting for a reply from the OP or another party label Apr 28, 2025
@mdm317 mdm317 requested a review from kirkwaiblinger April 30, 2025 13:55
@github-actions github-actions bot removed the awaiting response Issues waiting for a reply from the OP or another party label Apr 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bug: @typescript-eslint/prefer-nullish-coalescing mal-fixes nested condition
3 participants