【问题标题】:how to use typescript Compiler API to get normal function info, eg: returnType/parameters?如何使用 typescript Compiler API 获取正常的函数信息,例如:returnType/parameters?
【发布时间】:2018-04-23 05:27:40
【问题描述】:
/**
 * class of User
 */
class User {
    /**
     * constructor
     * @param name c-name
     */
    constructor(name: string) {
        this.name = name
    }
    /**
     * property name
     */
    private name: string
    /**
     * setName
     * @param name f-name
     */
    public setName(name: string) {
        this.name = name
    }
}

我看到了Typescript Wiki,我可以得到构造函数的信息,例如:returnType/parameters。

[
    {
        "name": "User",
        "documentation": "class of User",
        "type": "typeof User",
        "constructors": [
            {
                "parameters": [
                    {
                        "name": "name",
                        "documentation": "c-name",
                        "type": "string"
                    }
                ],
                "returnType": "User",
                "documentation": "constructor"
            }
        ]
    }
]

但我想获得关于正常功能 getName 的 returnType/parameters/documentation 的信息,我该怎么做?

ps:我知道构造函数有签名,签名有函数getReturntype,但是普通函数没有签名,所以无法获取信息

谢谢!

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    假设您知道如何获取MethodDeclaration,那么以下将起作用:

    // I'm assuming you know how to get the type checker from the compiler too.
    const typeChecker = ...;
    // Navigate through the tree to get to the method declaration located in the class.
    // This is the node with kind === ts.SyntaxKind.MethodDeclaration or
    // you can use ts.isMethodDeclaration(node)
    const methodDeclaration = ... as ts.MethodDeclaration;
    
    const signature = typeChecker.getSignatureFromDeclaration(methodDeclaration);
    const returnType = typeChecker.getReturnTypeOfSignature(signature);
    const parameters = methodDeclaration.parameters; // array of Parameters
    const docs = methodDeclaration.jsDoc; // array of js docs
    

    顺便说一句,你应该看看我写的这个AST viewer。它可能会帮助您解决将来遇到的一些问题。此外,根据您的用例,ts-morph 将有助于更轻松地导航和操作 AST。

    【讨论】:

    • 谢谢!我喜欢这种方法: const signature = checker.getSignatureFromDeclaration(method)
    • 非常感谢!在编译器 api 上找到文档相当困难......你知道getSignatureFromDeclaration 将返回undefined 的任何情况吗?我没能做到,但它在签名中......
    • @Gerrit0 最好看源码。请参阅checker.ts 中的getSignatureFromDeclaration
    • 如果返回类型是某种数组,这似乎不起作用。 returnType 总是 any
    猜你喜欢
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 2017-12-30
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多