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

Is there a function to print a definition as a string

我想将classes、函数、方法等的definition/declaration打印成字符串。下面是 vscode 如何显示 class 方法声明的示例:(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)
);