如何将 JSDoc 注释添加到使用打字稿 AST api 生成的打字稿?

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

如何使用 typescript 的 AST api 和打印机来创建带有文档注释的函数?

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

以下代码生成函数。

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);

目前不支持发出 JSDoc 注释。 TypeScript 存储库中存在未解决的问题:https://github.com/microsoft/TypeScript/issues/17146.

作为解决方法,我能做的最接近的方法是使用 ts.addSyntheticLeadingComment 作为:

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

得到以下输出:

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