Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-condition] improve optional chain…
Browse files Browse the repository at this point in the history
… handling (#2111)
  • Loading branch information
yeonjuan committed May 30, 2020
1 parent d7d4eeb commit 9ee399b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
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,
},
],
},
],
});

0 comments on commit 9ee399b

Please sign in to comment.