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

feat(eslint-plugin): add rule prefer-optional-chain #1213

Merged
merged 5 commits into from Nov 24, 2019

Conversation

bradzacher
Copy link
Member

@bradzacher bradzacher commented Nov 16, 2019

Super straightforward implementation.
Didn't even need type information (just assumes the user has written type-correct code).

Will detect:

foo && foo.a && foo.a.b && foo.a.b.c;
foo && foo['a'] && foo['a'].b && foo['a'].b.c;
foo && foo.a && foo.a.b && foo.a.b.method && foo.a.b.method();

// this rule also supports converting chained strict nullish checks:
foo &&
  foo.a != null &&
  foo.a.b !== null &&
  foo.a.b.c != undefined &&
  foo.a.b.c.d !== undefined &&
  foo.a.b.c.d.e;

OFC provides a fixer, which will fix the above to:

foo?.a?.b?.c;
foo?.['a']?.b?.c;
foo?.a?.b?.method?.();

foo?.a?.b?.c?.d?.e;

@bradzacher bradzacher added the enhancement: new plugin rule New rule request for eslint-plugin label Nov 16, 2019
@typescript-eslint

This comment has been minimized.

@merlinnot
Copy link

merlinnot commented Nov 16, 2019

Thank you for picking this up! Do you think it would be possible to handle on more pattern here?

a !== undefined && a.b !== undefined && a.b.c !== undefined

This is often used to alleviate the unsafety of &&.

@bradzacher bradzacher merged commit ad7e1a7 into master Nov 24, 2019
@bradzacher bradzacher deleted the prefer-optional-chain branch November 24, 2019 22:26
@turadg
Copy link

turadg commented Dec 23, 2019

Thanks for this!

User caveat: the fixer loses comments on the clipped ranges

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement: new plugin rule New rule request for eslint-plugin
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants