diff --git a/src/services/codefixes/convertTypedefToType.ts b/src/services/codefixes/convertTypedefToType.ts index 51e6290d46e11..20b8b2dcfe20e 100644 --- a/src/services/codefixes/convertTypedefToType.ts +++ b/src/services/codefixes/convertTypedefToType.ts @@ -6,6 +6,7 @@ import { import { Diagnostics, factory, + findAncestor, flatMap, getNewLineOrDefaultFromHost, getSynthesizedDeepClone, @@ -122,7 +123,26 @@ function doChange( } } - changes.replaceRange(sourceFile, { pos, end }, declaration, { prefix, suffix }); + const classParent = findAncestor(node, n => n.kind === SyntaxKind.ClassDeclaration); + + if (classParent) { + changes.insertNodeBefore( + sourceFile, + classParent, + declaration, + /*blankLineBetween*/ false, + ); + // Replace the current node with an empty line + changes.replaceNodeWithText(sourceFile, node, ""); + + // Exit the function as the changes are already applied + return; + } + + changes.replaceRange(sourceFile, { pos, end }, declaration, { + prefix, + suffix, + }); } function getLeftAndRightSiblings(typedefNode: JSDocTypedefTag): { leftSibling?: Node; rightSibling?: Node; } { diff --git a/tests/cases/fourslash/codeFixConvertTypedefToType8.ts b/tests/cases/fourslash/codeFixConvertTypedefToType8.ts new file mode 100644 index 0000000000000..399b4fa505eb2 --- /dev/null +++ b/tests/cases/fourslash/codeFixConvertTypedefToType8.ts @@ -0,0 +1,31 @@ +/// + +//// class Example { +//// /** +//// * List of items to be rendered in the bar chart +//// * @typedef {{ count: number }} Counter +//// * @returns {Counter} +//// */ +//// get something() { +//// return { count: 0 }; +//// } +//// } +//// + +verify.codeFix({ + description: ts.Diagnostics.Convert_typedef_to_TypeScript_type.message, + index: 0, + newFileContent: +`type Counter = { count: number; }; +class Example { + /** + * List of items to be rendered in the bar chart + * + * @returns {Counter} + */ + get something() { + return { count: 0 }; + } +} +`, +});