如何将 JSDoc 注释添加到使用 typescript AST api 生成的 typescript 中?

2024-03-25

如何使用 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 https://github.com/microsoft/TypeScript/issues/17146.

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

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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 JSDoc 注释添加到使用 typescript AST api 生成的 typescript 中? 的相关文章

随机推荐