From fed89f24ebe42a6412f0eb19949d5d4771656189 Mon Sep 17 00:00:00 2001 From: Brad Zacher Date: Tue, 1 Dec 2020 13:07:19 -0800 Subject: [PATCH] fix(eslint-plugin): [method-signature-style] fix crash with methods without a return type (#2836) Fixes #2834 --- .../src/rules/method-signature-style.ts | 19 ++++++++++--------- .../rules/method-signature-style.test.ts | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/packages/eslint-plugin/src/rules/method-signature-style.ts b/packages/eslint-plugin/src/rules/method-signature-style.ts index de6f366b673..54e68b2c671 100644 --- a/packages/eslint-plugin/src/rules/method-signature-style.ts +++ b/packages/eslint-plugin/src/rules/method-signature-style.ts @@ -82,7 +82,11 @@ export default util.createRule({ function getMethodReturnType( node: TSESTree.TSMethodSignature | TSESTree.TSFunctionType, ): string { - return sourceCode.getText(node.returnType!.typeAnnotation); + return node.returnType == null + ? // if the method has no return type, it implicitly has an `any` return type + // we just make it explicit here so we can do the fix + 'any' + : sourceCode.getText(node.returnType.typeAnnotation); } function getDelimiter(node: TSESTree.Node): string { @@ -149,16 +153,13 @@ export default util.createRule({ methodNode, ...duplicatedKeyMethodNodes, ].sort((a, b) => (a.range[0] < b.range[0] ? -1 : 1)); - const typeString = methodNodes.reduce( - (str, node, idx, nodes) => { + const typeString = methodNodes + .map(node => { const params = getMethodParams(node); const returnType = getMethodReturnType(node); - return `${str}(${params} => ${returnType})${ - idx !== nodes.length - 1 ? ' & ' : '' - }`; - }, - '', - ); + return `(${params} => ${returnType})`; + }) + .join(' & '); const key = getMethodKey(methodNode); const delimiter = getDelimiter(methodNode); yield fixer.replaceText( diff --git a/packages/eslint-plugin/tests/rules/method-signature-style.test.ts b/packages/eslint-plugin/tests/rules/method-signature-style.test.ts index e322c63c6a3..e82ee2e750b 100644 --- a/packages/eslint-plugin/tests/rules/method-signature-style.test.ts +++ b/packages/eslint-plugin/tests/rules/method-signature-style.test.ts @@ -427,5 +427,24 @@ declare const Foo: { }, ], }, + // https://github.com/typescript-eslint/typescript-eslint/issues/2834 + { + code: ` +interface MyInterface { + methodReturningImplicitAny(); +} + `, + output: ` +interface MyInterface { + methodReturningImplicitAny: () => any; +} + `, + errors: [ + { + messageId: 'errorMethod', + line: 3, + }, + ], + }, ], });