benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issue when printing TSTypeParameterInstantiation

ken-kenware opened this issue Β· comments

Hi! πŸ‘‹

Thanks for your work on this project!

I'm working on a project and encountered an issue with printing TSTypeParameterInstantiations if they had a comment in them. So parsing/printing this code:

const foo = new Array<
   // A comment here
  number> = []

Results in the following block, which is not valid TypeScript Syntax:

const foo = new Array<// A comment here
number> = []

I was able to use patch-package to patch recast for the project I'm working on, and I am happy to open a PR for the fix as well.

Here is the diff that solved my problem:

diff --git a/node_modules/recast/lib/printer.js b/node_modules/recast/lib/printer.js
index 8cbc392..470b3c4 100644
--- a/node_modules/recast/lib/printer.js
+++ b/node_modules/recast/lib/printer.js
@@ -1730,8 +1730,12 @@ function genericPrintNoParens(path, options, print) {
         }
         case "TSTypeParameterDeclaration":
         case "TSTypeParameterInstantiation":
+          // If the first parameter has a comment, we want to insert a new line to avoid causing a syntax error:
+          const parameterNode = path.getValue()
+          const [firstParam] = parameterNode.params || [];
             return lines_1.concat([
                 "<",
+                firstParam && firstParam.comments  && firstParam.comments.length ? lines_1.fromString("\n") : lines_1.fromString(""),
                 lines_1.fromString(", ").join(path.map(print, "params")),
                 ">",
             ]);

This issue body was partially generated by patch-package.

Thanks! A PR would be appreciated.