Skip to content

Commit 9ee399b

Browse files
authored
fix(eslint-plugin): [no-unnecessary-condition] improve optional chain handling (typescript-eslint#2111)
1 parent d7d4eeb commit 9ee399b

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

packages/eslint-plugin/src/rules/no-unnecessary-condition.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
isNullableType,
2121
nullThrows,
2222
NullThrowsReasons,
23+
isMemberOrOptionalMemberExpression,
2324
} from '../util';
2425

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

442-
const type = getNodeType(node);
443+
const nodeToCheck = isMemberOrOptionalMemberExpression(node)
444+
? node.object
445+
: node;
446+
const type = getNodeType(nodeToCheck);
447+
443448
if (
444449
isTypeFlagSet(type, ts.TypeFlags.Any) ||
445450
isTypeFlagSet(type, ts.TypeFlags.Unknown) ||

packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -724,5 +724,62 @@ foo
724724
},
725725
],
726726
},
727+
{
728+
code: `
729+
declare const x: { a?: { b: string } };
730+
x?.a?.b;
731+
`,
732+
output: `
733+
declare const x: { a?: { b: string } };
734+
x.a?.b;
735+
`,
736+
errors: [
737+
{
738+
messageId: 'neverOptionalChain',
739+
line: 3,
740+
endLine: 3,
741+
column: 2,
742+
endColumn: 4,
743+
},
744+
],
745+
},
746+
{
747+
code: `
748+
declare const x: { a: { b?: { c: string } } };
749+
x.a?.b?.c;
750+
`,
751+
output: `
752+
declare const x: { a: { b?: { c: string } } };
753+
x.a.b?.c;
754+
`,
755+
errors: [
756+
{
757+
messageId: 'neverOptionalChain',
758+
line: 3,
759+
endLine: 3,
760+
column: 4,
761+
endColumn: 6,
762+
},
763+
],
764+
},
765+
{
766+
code: `
767+
let x: { a?: string };
768+
x?.a;
769+
`,
770+
output: `
771+
let x: { a?: string };
772+
x.a;
773+
`,
774+
errors: [
775+
{
776+
messageId: 'neverOptionalChain',
777+
line: 3,
778+
endLine: 3,
779+
column: 2,
780+
endColumn: 4,
781+
},
782+
],
783+
},
727784
],
728785
});

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy