是否有将定义打印为字符串的函数



我想将类、函数、方法等的定义/声明打印为字符串。以下是vscode如何显示类方法声明的示例:(method) TestClass.testMethod(): void,我想实现类似的功能。现在,有这个函数吗,或者我需要通过提取ast来自己做吗?

编译器API或多或少对我来说是未知的,这是我打印节点的尝试。第一个代码块是输入代码;提取器";密码

我也很感激参考资料,在那里我可以找到更多关于这方面的信息,例子,文档,任何东西。

export class TestClass {
// This is the method declaration node
testMethod(arg: string) {}
}

const node: ts.MethodDeclaration
checker.typeToString(checker.getTypeAtLocation(node))
// output: (arg: string) => void
printer.printNode(ts.EmitHint.Unspecified, node, sourceFile)
// output: testMethod(arg: string) {}
// wanted: testMethod(arg: string): void

可能有更好的方法,但有一种方法是获取签名,然后调用TypeChecker#signatureToString:

const signature = typeChecker.getSignatureFromDeclaration(node);
// outputs: testMethod(arg: string): void
console.log(
node.name.getText(sourceFile)
+ typeChecker.signatureToString(signature, node)
);

最新更新