/**
* 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
}
}
我看到了打字稿 Wiki,我可以获取构造函数的信息,例如:返回类型/参数。
[
{
"name": "User",
"documentation": "class of User",
"type": "typeof User",
"constructors": [
{
"parameters": [
{
"name": "name",
"documentation": "c-name",
"type": "string"
}
],
"returnType": "User",
"documentation": "constructor"
}
]
}
]
但是我想在普通函数getName上获取返回类型/参数/文档的信息,我该怎么做?
ps:I知道构造函数有签名,签名有函数getReturntype,但普通函数没有签名,所以我无法获取信息
谢谢!
假设您知道如何获取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查看器。它可能会帮助您解决将来遇到的一些问题。此外,根据您的用例,ts-morph 将有助于使导航和操作 AST 更容易一些。