Skip to content

Commit

Permalink
fix: TSTypeAnnotation printer when parent is a TSFunction type
Browse files Browse the repository at this point in the history
  • Loading branch information
henryqdineen committed Jun 12, 2024
1 parent 887f5b7 commit ead67b6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down
28 changes: 28 additions & 0 deletions test/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;");
});
});

0 comments on commit ead67b6

Please sign in to comment.