Search code examples
typescriptcode-generation

How do I add JSDoc comments to typescript generated with the typescript AST api?


How do I use typescript's AST api and printer to create a function with a doc comment?

/**
 * foo function
 */
function foo () {}

The following code generates the function.

function foo () {}
import ts from 'typescript';
const fooFunction = ts.createFunctionDeclaration(
  undefined,
  undefined,
  undefined,
  ts.createIdentifier("foo"),
  undefined,
  [],
  undefined,
  ts.createBlock(
    [],
    false
  )
)

const printer = ts.createPrinter({    
  newLine: ts.NewLineKind.LineFeed,    
});    

const resultFile = ts.createSourceFile(    
  "example.ts",    
  "",    
  ts.ScriptTarget.Latest,    
  /*setParentNodes*/ false,    
  ts.ScriptKind.TS      
);

const result = printer.printNode(
  ts.EmitHint.Unspecified,
  fooFunction,
  resultFile
);

console.log(result);

Solution

  • Presently, emitting JSDoc comments is not supported. There is an open issue in TypeScript repository: https://github.com/microsoft/TypeScript/issues/17146.

    As a workaround, the closest I was able to do is by using ts.addSyntheticLeadingComment as:

    const node = makeFactorialFunction();
    ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, 'foo bar', true);
    

    which got me the following output:

    /*foo bar*/
    export function factorial(n): number {
        if (n <= 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }