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

fix(eslint-plugin): [prefer-optional-chain] only look at left operand for requireNullish #8559

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
5c5a4c2
ignore right
abrahamguo Feb 27, 2024
d74cc6c
invert check
abrahamguo Feb 27, 2024
2e3eec3
invert
abrahamguo Feb 27, 2024
3e22435
add failing case
abrahamguo Feb 27, 2024
08681ed
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Feb 27, 2024
14d3aeb
move operator check
abrahamguo Feb 27, 2024
cece182
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Mar 1, 2024
0e4fcf4
WIP
abrahamguo Mar 4, 2024
fe06a96
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Mar 5, 2024
3969122
WIP
abrahamguo Mar 7, 2024
703b3c7
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Mar 11, 2024
d6ff24c
pull check out
abrahamguo Mar 11, 2024
2833796
lint
abrahamguo Mar 11, 2024
52f9448
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Mar 12, 2024
386d63c
add tests
abrahamguo Mar 12, 2024
2738405
add output
abrahamguo Mar 12, 2024
5e04ce9
quotes
abrahamguo Mar 12, 2024
c9f0c62
finish tests
abrahamguo Mar 12, 2024
4747282
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Mar 13, 2024
ed4aaa7
remove last child
abrahamguo Mar 13, 2024
8b88d03
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Mar 13, 2024
606e1f6
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Mar 16, 2024
fd2b38f
add a few more tests
abrahamguo Mar 16, 2024
b9fc141
Merge branch 'main' of github.com:abrahamguo/typescript-eslint into p…
abrahamguo Apr 7, 2024
2bba0ac
remove skipvalidation
abrahamguo Apr 7, 2024
15d7dbc
update snapshots
abrahamguo Apr 7, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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),
),
)
abrahamguo marked this conversation as resolved.
Show resolved Hide resolved
) {
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,
abrahamguo marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -1895,6 +1937,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