-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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] handle more cases #1261
Conversation
Thanks for the PR, @bradzacher! 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. As a thank you, your profile/company logo will be added to our main README which receives thousands of unique visitors per day. |
Codecov Report
@@ Coverage Diff @@
## master #1261 +/- ##
==========================================
- Coverage 94.1% 94.07% -0.03%
==========================================
Files 130 131 +1
Lines 5681 5737 +56
Branches 1596 1616 +20
==========================================
+ Hits 5346 5397 +51
- Misses 182 184 +2
- Partials 153 156 +3
|
c22ad6f
to
b068709
Compare
const x = {y: 0};
if (x["y"] !== undefined && x["y"] !== null) {
//
} ... is currently being reported, fixed to: const x = {y: 0};
if (x["y"]) {
//
} This doesn't seem right at all. My real-world example actually looks like this: const field = `relatedArticleIds${i}`;
if (data[field] !== undefined && data[field] !== null) {
relatedArticleIds.push(data[field]);
} (i.e. it uses a dynamic index) The fix doesn't actually use optional chaining, and the code is not equivalent (checking for not Will this be fixed here (has it already been?), or should I open a separate issue for it? |
@glen-84 - that issue is fixed by this PR. |
I imported my implementation to the fb codebase and ran it (because I figured this rule isn't actually TS specific), and I found a few cases that I missed in the original implementation.
To better handle the cases, I significantly reduced the "allowed" scope of the rule by only allowing certain AST structures (see the
isValidChainTarget
function).Changes:
at detection time:
foo && fooBar.baz
foo && foo.bar?.baz
foo && foo[bar as string] && foo[bar as string].baz
, orfoo && foo[1 + 2] && foo[1 + 2].baz
.at fix time:
foo && foo.map(bar => <Baz bar={bar} />)
foo?.map(bar => <Baz bar={bar} />)
foo && foo.map(bar => typeof bar)
foo?.map(bar => typeof bar)
foo && foo.bar(/* comment */a, )
foo?.bar(/* comment */a, )
foo && foo['bar baz']
foo?.['bar baz']
foo != null && foo.bar != null
foo?.bar != null
foo && foo.bar != null && baz
foo?.bar != null && baz