From 9ee399b5906e82f346ff89141207a6630786de54 Mon Sep 17 00:00:00 2001 From: YeonJuan Date: Sun, 31 May 2020 06:48:14 +0900 Subject: [PATCH] fix(eslint-plugin): [no-unnecessary-condition] improve optional chain handling (#2111) --- .../src/rules/no-unnecessary-condition.ts | 7 ++- .../rules/no-unnecessary-condition.test.ts | 57 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts index 1c73614c8a7..316b4fcd76a 100644 --- a/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts +++ b/packages/eslint-plugin/src/rules/no-unnecessary-condition.ts @@ -20,6 +20,7 @@ import { isNullableType, nullThrows, NullThrowsReasons, + isMemberOrOptionalMemberExpression, } from '../util'; const typeContainsFlag = (type: ts.Type, flag: ts.TypeFlags): boolean => { @@ -439,7 +440,11 @@ export default createRule({ 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) || diff --git a/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts b/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts index 72bf643942f..fa3d1e6fc3b 100644 --- a/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts +++ b/packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts @@ -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, + }, + ], + }, ], });