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): [no-unnecessary-condition] improve optional chain handling #2111

Merged
merged 4 commits into from May 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 6 additions & 1 deletion packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Expand Up @@ -20,6 +20,7 @@ import {
isNullableType,
nullThrows,
NullThrowsReasons,
isMemberOrOptionalMemberExpression,
} from '../util';

const typeContainsFlag = (type: ts.Type, flag: ts.TypeFlags): boolean => {
Expand Down Expand Up @@ -439,7 +440,11 @@ export default createRule<Options, MessageId>({
return;
}

const type = getNodeType(node);
const nodeToCheck = isMemberOrOptionalMemberExpression(node)
? node.object
: node;
const type = getNodeType(nodeToCheck);

if (
isTypeFlagSet(type, ts.TypeFlags.Any) ||
isTypeFlagSet(type, ts.TypeFlags.Unknown) ||
Expand Down
Expand Up @@ -724,5 +724,62 @@ foo
},
],
},
{
code: `
declare const x: { a?: { b: string } };
x?.a?.b;
`,
output: `
declare const x: { a?: { b: string } };
x.a?.b;
`,
errors: [
{
messageId: 'neverOptionalChain',
line: 3,
endLine: 3,
column: 2,
endColumn: 4,
},
],
},
{
code: `
declare const x: { a: { b?: { c: string } } };
x.a?.b?.c;
`,
output: `
declare const x: { a: { b?: { c: string } } };
x.a.b?.c;
`,
errors: [
{
messageId: 'neverOptionalChain',
line: 3,
endLine: 3,
column: 4,
endColumn: 6,
},
],
},
{
code: `
let x: { a?: string };
x?.a;
`,
output: `
let x: { a?: string };
x.a;
`,
errors: [
{
messageId: 'neverOptionalChain',
line: 3,
endLine: 3,
column: 2,
endColumn: 4,
},
],
},
],
});