From ead67b6a540ed3350c53686a4ef57388222c5185 Mon Sep 17 00:00:00 2001 From: Henry Dineen Date: Wed, 12 Jun 2024 15:22:48 -0400 Subject: [PATCH] fix: TSTypeAnnotation printer when parent is a TSFunction type --- lib/printer.ts | 12 ++++++++++-- test/printer.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/lib/printer.ts b/lib/printer.ts index e3f834f0..d3d0aab4 100644 --- a/lib/printer.ts +++ b/lib/printer.ts @@ -2307,8 +2307,16 @@ function genericPrintNoParens(path: any, options: any, print: any) { case "TSNonNullExpression": return concat([path.call(print, "expression"), "!"]); - case "TSTypeAnnotation": - return concat([": ", path.call(print, "typeAnnotation")]); + case "TSTypeAnnotation": { + const isFunctionType = namedTypes.TSFunctionType.check( + path.getParentNode(0), + ); + + return concat([ + isFunctionType ? "=> " : ": ", + path.call(print, "typeAnnotation"), + ]); + } case "TSIndexSignature": return concat([ diff --git a/test/printer.ts b/test/printer.ts index e25a961d..313408c0 100644 --- a/test/printer.ts +++ b/test/printer.ts @@ -2600,4 +2600,32 @@ describe("printer", function () { ), ); }); + + it("should reprint TSTypeAnnotation correctly", function () { + const code = "type Foo = () => Bar;"; + + const ast = parse(code, { + parser: tsParser, + }); + + recast.visit(ast, { + visitTSTypeReference(path) { + if ( + path.node.typeName.type === "Identifier" && + path.node.typeName.name === "Bar" && + path.parentPath.node.type === "TSTypeAnnotation" + ) { + path.replace( + b.tsQualifiedName(b.identifier("Bar"), b.identifier("Baz")), + ); + } + + this.traverse(path); + }, + }); + + const pretty = new Printer().print(ast).code; + + assert.strictEqual(pretty, "type Foo = () => Bar.Baz;"); + }); });