Skip to content

Commit

Permalink
fix(eslint-plugin): [prefer-optional-chain] only look at left operand…
Browse files Browse the repository at this point in the history
… for `requireNullish` (#8559)

* ignore right

* invert check

* invert

* add failing case

* move operator check

* WIP

* WIP

* pull check out

* lint

* add tests

* add output

* quotes

* finish tests

* remove last child

* add a few more tests

* remove skipvalidation

* update snapshots
  • Loading branch information
abrahamguo committed Apr 22, 2024
1 parent 9e0d9f5 commit eef257b
Show file tree
Hide file tree
Showing 7 changed files with 189 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ When this option is `true` the rule will skip operands that are not typed with `

<TabItem value="❌ Incorrect for `requireNullish: true`">

```ts option='{ "requireNullish": true }' skipValidation
```ts option='{ "requireNullish": true }'
declare const thing1: string | null;
thing1 && thing1.toString();
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
NullThrowsReasons,
OperatorPrecedence,
} from '../../util';
import { checkNullishAndReport } from './checkNullishAndReport';
import { compareNodes, NodeComparisonResult } from './compareNodes';
import type { ValidOperand } from './gatherLogicalOperands';
import { NullishComparisonType } from './gatherLogicalOperands';
Expand Down Expand Up @@ -493,20 +494,26 @@ export function analyzeChain(
): void => {
if (subChain.length > 1) {
const subChainFlat = subChain.flat();
context.report({
messageId: 'preferOptionalChain',
loc: {
start: subChainFlat[0].node.loc.start,
end: subChainFlat[subChainFlat.length - 1].node.loc.end,
checkNullishAndReport(
context,
parserServices,
options,
subChainFlat.slice(0, -1).map(({ node }) => node),
{
messageId: 'preferOptionalChain',
loc: {
start: subChainFlat[0].node.loc.start,
end: subChainFlat[subChainFlat.length - 1].node.loc.end,
},
...getFixer(
context.sourceCode,
parserServices,
operator,
options,
subChainFlat,
),
},
...getFixer(
context.sourceCode,
parserServices,
operator,
options,
subChainFlat,
),
});
);
}

// we've reached the end of a chain of logical expressions
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { isTypeFlagSet } from '@typescript-eslint/type-utils';
import type {
ParserServicesWithTypeInformation,
TSESTree,
} from '@typescript-eslint/utils';
import type {
ReportDescriptor,
RuleContext,
} from '@typescript-eslint/utils/ts-eslint';
import { unionTypeParts } from 'ts-api-utils';
import * as ts from 'typescript';

import type {
PreferOptionalChainMessageIds,
PreferOptionalChainOptions,
} from './PreferOptionalChainOptions';

export function checkNullishAndReport(
context: RuleContext<
PreferOptionalChainMessageIds,
[PreferOptionalChainOptions]
>,
parserServices: ParserServicesWithTypeInformation,
{ requireNullish }: PreferOptionalChainOptions,
maybeNullishNodes: TSESTree.Expression[],
descriptor: ReportDescriptor<PreferOptionalChainMessageIds>,
): void {
if (
!requireNullish ||
maybeNullishNodes.some(node =>
unionTypeParts(parserServices.getTypeAtLocation(node)).some(t =>
isTypeFlagSet(t, ts.TypeFlags.Null | ts.TypeFlags.Undefined),
),
)
) {
context.report(descriptor);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,6 @@ function isValidFalseBooleanCheckType(
}
}

if (options.requireNullish === true) {
return types.some(t => isTypeFlagSet(t, NULLISH_FLAGS));
}

let allowedFlags = NULLISH_FLAGS | ts.TypeFlags.Object;
if (options.checkAny === true) {
allowedFlags |= ts.TypeFlags.Any;
Expand Down
5 changes: 3 additions & 2 deletions packages/eslint-plugin/src/rules/prefer-optional-chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
OperatorPrecedence,
} from '../util';
import { analyzeChain } from './prefer-optional-chain-utils/analyzeChain';
import { checkNullishAndReport } from './prefer-optional-chain-utils/checkNullishAndReport';
import type { ValidOperand } from './prefer-optional-chain-utils/gatherLogicalOperands';
import {
gatherLogicalOperands,
Expand Down Expand Up @@ -141,9 +142,9 @@ export default createRule<

return leftPrecedence < OperatorPrecedence.LeftHandSide;
}
context.report({
node: parentNode,
checkNullishAndReport(context, parserServices, options, [leftNode], {
messageId: 'preferOptionalChain',
node: parentNode,
suggest: [
{
messageId: 'optionalChainSuggest',
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -815,22 +815,64 @@ describe('hand-crafted cases', () => {
declare const x: string;
x && x.length;
`,
options: [
{
requireNullish: true,
},
],
options: [{ requireNullish: true }],
},
{
code: `
declare const foo: string;
foo && foo.toString();
`,
options: [{ requireNullish: true }],
},
{
code: `
declare const x: string | number | boolean | object;
x && x.toString();
`,
options: [
{
requireNullish: true,
},
],
options: [{ requireNullish: true }],
},
{
code: `
declare const foo: { bar: string };
foo && foo.bar && foo.bar.toString();
`,
options: [{ requireNullish: true }],
},
{
code: `
declare const foo: string;
foo && foo.toString() && foo.toString();
`,
options: [{ requireNullish: true }],
},
{
code: `
declare const foo: { bar: string };
foo && foo.bar && foo.bar.toString() && foo.bar.toString();
`,
options: [{ requireNullish: true }],
},
{
code: `
declare const foo1: { bar: string | null };
foo1 && foo1.bar;
`,
options: [{ requireNullish: true }],
},
{
code: `
declare const foo: string;
(foo || {}).toString();
`,
options: [{ requireNullish: true }],
},

{
code: `
declare const foo: string | null;
(foo || 'a' || {}).toString();
`,
options: [{ requireNullish: true }],
},
{
code: `
Expand Down Expand Up @@ -1898,6 +1940,80 @@ describe('hand-crafted cases', () => {
],
},

// requireNullish
{
code: `
declare const thing1: string | null;
thing1 && thing1.toString();
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
declare const thing1: string | null;
thing1 && thing1.toString() && true;
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
declare const foo: string | null;
foo && foo.toString() && foo.toString();
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
declare const foo: { bar: string | null | undefined } | null | undefined;
foo && foo.bar && foo.bar.toString();
`,
output: `
declare const foo: { bar: string | null | undefined } | null | undefined;
foo?.bar?.toString();
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
declare const foo: { bar: string | null | undefined } | null | undefined;
foo && foo.bar && foo.bar.toString() && foo.bar.toString();
`,
output: `
declare const foo: { bar: string | null | undefined } | null | undefined;
foo?.bar?.toString() && foo.bar.toString();
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
declare const foo: string | null;
(foo || {}).toString();
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
declare const foo: string;
(foo || undefined || {}).toString();
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},
{
code: `
declare const foo: string | null;
(foo || undefined || {}).toString();
`,
options: [{ requireNullish: true }],
errors: [{ messageId: 'preferOptionalChain' }],
},

// allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing
{
code: `
Expand Down

0 comments on commit eef257b

Please sign in to comment.