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);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With