Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use typescript Compiler API to get normal function info, eg: returnType/parameters?

/**
 * 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
    }
}

I saw the Typescript Wiki and I can get the constructor's info, eg: returnType/parameters.

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

but i want t get the infomation of returnType/parameters/documentation on normal function getName , how can i do this?

ps:I know the constructor has the signatures, signatures has a function getReturntype, but the normal functions has no signatures, so i can not get the info

thanks!

like image 574
sunhaikuo Avatar asked Feb 04 '23 03:02

sunhaikuo


1 Answers

Assuming you know how to get the MethodDeclaration, then the following will work:

// 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

By the way, you should check out this AST viewer I wrote. It might help you with some future questions you have. Also, depending on your use case, ts-morph which will help make navigating and manipulating the AST a little easier.

like image 81
David Sherret Avatar answered Apr 25 '23 22:04

David Sherret