如何将JSDoc注释添加到使用TypeScrip AST API生成的类型脚本中? [英] How do I add JSDoc comments to typescript generated with the typescript AST api?

查看:13
本文介绍了如何将JSDoc注释添加到使用TypeScrip AST API生成的类型脚本中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用TypeScrip的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注释。打字脚本存储库中存在未解决的问题:https://github.com/microsoft/TypeScript/issues/17146

作为一种解决办法,我所能做的最接近的方法是使用ts.addSyntheticLeadingCommentAS:

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

这篇关于如何将JSDoc注释添加到使用TypeScrip AST API生成的类型脚本中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆