From 4579245f36d9c3deccb097da9d5545f9c5c1ab26 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sat, 27 Aug 2022 01:43:19 +0300 Subject: [PATCH] fix(50427): allow convert function expressions (#50430) --- .../codefixes/convertFunctionToEs6Class.ts | 6 +++--- .../fourslash/convertFunctionToEs6Class14.ts | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 tests/cases/fourslash/convertFunctionToEs6Class14.ts diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index 6704410afd279..7cc67e1049c8b 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -22,8 +22,8 @@ namespace ts.codefix { } const ctorDeclaration = ctorSymbol.valueDeclaration; - if (isFunctionDeclaration(ctorDeclaration)) { - changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunctionDeclaration(ctorDeclaration)); + if (isFunctionDeclaration(ctorDeclaration) || isFunctionExpression(ctorDeclaration)) { + changes.replaceNode(sourceFile, ctorDeclaration, createClassFromFunction(ctorDeclaration)); } else if (isVariableDeclaration(ctorDeclaration)) { const classDeclaration = createClassFromVariableDeclaration(ctorDeclaration); @@ -233,7 +233,7 @@ namespace ts.codefix { return cls; } - function createClassFromFunctionDeclaration(node: FunctionDeclaration): ClassDeclaration { + function createClassFromFunction(node: FunctionDeclaration | FunctionExpression): ClassDeclaration { const memberElements = createClassElementsFromSymbol(ctorSymbol); if (node.body) { memberElements.unshift(factory.createConstructorDeclaration(/*modifiers*/ undefined, node.parameters, node.body)); diff --git a/tests/cases/fourslash/convertFunctionToEs6Class14.ts b/tests/cases/fourslash/convertFunctionToEs6Class14.ts new file mode 100644 index 0000000000000..22535833abfa5 --- /dev/null +++ b/tests/cases/fourslash/convertFunctionToEs6Class14.ts @@ -0,0 +1,18 @@ +/// + +// @allowNonTsExtensions: true +// @filename: foo.js +////const NS = {}; +////NS.Foo = function () {}; +////NS.Foo.prototype.m = function () {}; + +verify.codeFix({ + description: "Convert function to an ES2015 class", + newFileContent: +`const NS = {}; +NS.Foo = class { + constructor() { } + m() { } +}; +` +});