From 898dd3961944a5da3a129e9eba02634286e7aee4 Mon Sep 17 00:00:00 2001 From: Armano Date: Fri, 5 Feb 2021 16:59:48 +0100 Subject: [PATCH] fix(eslint-plugin): [prefer-function-type] correct fixer when signature ends with a semi (#3002) --- .../src/rules/prefer-function-type.ts | 11 ++++-- .../tests/rules/prefer-function-type.test.ts | 34 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/packages/eslint-plugin/src/rules/prefer-function-type.ts b/packages/eslint-plugin/src/rules/prefer-function-type.ts index 1d8c2701210..f6aad463930 100644 --- a/packages/eslint-plugin/src/rules/prefer-function-type.ts +++ b/packages/eslint-plugin/src/rules/prefer-function-type.ts @@ -88,6 +88,10 @@ export default util.createRule({ colonPos + 1, )}`; + const lastChar = suggestion.endsWith(';') ? ';' : ''; + if (lastChar) { + suggestion = suggestion.slice(0, -1); + } if (shouldWrapSuggestion(parent.parent)) { suggestion = `(${suggestion})`; } @@ -98,16 +102,17 @@ export default util.createRule({ .slice( parent.id.range[0], parent.typeParameters.range[1], - )} = ${suggestion}`; + )} = ${suggestion}${lastChar}`; } - return `type ${parent.id.name} = ${suggestion}`; + return `type ${parent.id.name} = ${suggestion}${lastChar}`; } - return suggestion.endsWith(';') ? suggestion.slice(0, -1) : suggestion; + return suggestion; } /** * @param member The TypeElement being checked * @param node The parent of member being checked + * @param tsThisTypes */ function checkMember( member: TSESTree.TypeElement, diff --git a/packages/eslint-plugin/tests/rules/prefer-function-type.test.ts b/packages/eslint-plugin/tests/rules/prefer-function-type.test.ts index d294041fbaf..71c2557fda4 100644 --- a/packages/eslint-plugin/tests/rules/prefer-function-type.test.ts +++ b/packages/eslint-plugin/tests/rules/prefer-function-type.test.ts @@ -268,5 +268,39 @@ type Foo = () => { }; `, }, + { + code: noFormat` +type X = {} | { (): void; } + `, + errors: [ + { + messageId: 'functionTypeOverCallableType', + type: AST_NODE_TYPES.TSCallSignatureDeclaration, + data: { + literalOrInterface: phrases[AST_NODE_TYPES.TSTypeLiteral], + }, + }, + ], + output: noFormat` +type X = {} | (() => void) + `, + }, + { + code: noFormat` +type X = {} & { (): void; }; + `, + errors: [ + { + messageId: 'functionTypeOverCallableType', + type: AST_NODE_TYPES.TSCallSignatureDeclaration, + data: { + literalOrInterface: phrases[AST_NODE_TYPES.TSTypeLiteral], + }, + }, + ], + output: noFormat` +type X = {} & (() => void); + `, + }, ], });