Skip to content

Commit

Permalink
feat(eslint-plugin): [prefer-optional-chain] support suggesting `!foo…
Browse files Browse the repository at this point in the history
… || !foo.bar` as a valid match for the rule (#5266)
  • Loading branch information
omril1 committed Aug 21, 2022
1 parent c950051 commit aca935c
Show file tree
Hide file tree
Showing 11 changed files with 476 additions and 102 deletions.
12 changes: 11 additions & 1 deletion packages/eslint-plugin/docs/rules/prefer-optional-chain.md
@@ -1,5 +1,5 @@
---
description: 'Enforce using concise optional chain expressions instead of chained logical ands.'
description: 'Enforce using concise optional chain expressions instead of chained logical ands, negated logical ors, or empty objects.'
---

> 🛑 This file is source code, not the primary documentation location! 🛑
Expand Down Expand Up @@ -65,9 +65,15 @@ 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();

// With empty objects
(((foo || {}).a || {}).b || {}).c;
(((foo || {})['a'] || {}).b || {}).c;

// With negated `or`s
!foo || !foo.bar;
!foo || !foo[bar];
!foo || !foo.bar || !foo.bar.baz || !foo.bar.baz();

// this rule also supports converting chained strict nullish checks:
foo &&
foo.a != null &&
Expand All @@ -85,6 +91,10 @@ foo?.['a']?.b?.c;
foo?.a?.b?.method?.();

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

!foo?.bar;
!foo?.[bar];
!foo?.bar?.baz?.();
```

**Note:** there are a few edge cases where this rule will false positive. Use your best judgement when evaluating reported errors.
Expand Down
Expand Up @@ -90,7 +90,7 @@ export default util.createRule<Options, MessageIds>({
| TSESTree.FunctionExpression
| TSESTree.FunctionDeclaration,
): boolean {
if (!options.allowedNames || !options.allowedNames.length) {
if (!options.allowedNames?.length) {
return false;
}

Expand Down
11 changes: 4 additions & 7 deletions packages/eslint-plugin/src/rules/no-useless-constructor.ts
Expand Up @@ -34,13 +34,10 @@ function checkAccessibility(node: TSESTree.MethodDefinition): boolean {
* Check if method is not useless due to typescript parameter properties and decorators
*/
function checkParams(node: TSESTree.MethodDefinition): boolean {
return (
!node.value.params ||
!node.value.params.some(
param =>
param.type === AST_NODE_TYPES.TSParameterProperty ||
param.decorators?.length,
)
return !node.value.params.some(
param =>
param.type === AST_NODE_TYPES.TSParameterProperty ||
param.decorators?.length,
);
}

Expand Down

0 comments on commit aca935c

Please sign in to comment.