Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: TSTypeAnnotation printer when parent is a TSFunction type #1404

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;");
});
});
Loading