【问题标题】:Is there a function to print a definition as a string是否有将定义打印为字符串的功能
【发布时间】:2022-01-10 23:08:05
【问题描述】:

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

Compiler 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

【问题讨论】:

    标签: typescript-compiler-api


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多