【问题标题】:Typescript Compiler API or Language Service get function argument typeTypescript Compiler API 或 Language Service 获取函数参数类型
【发布时间】:2017-12-30 15:49:22
【问题描述】:

我想使用 typescript 编译器 API 获取类的方法参数的类型以提供代码补全。

我的班级有方法byId(id: sap.ui.core.ID)。我想检查 byId() 方法是否有这个 id 参数。所以我开始输入this.byId(|),当我触发代码完成时,我想获取该位置的类型,如果正确,我会在 XML 文件中查找完成项。

如果我使用 LanguageService 类,它只会在括号后列出类型。编译器 API 和类型检查器没有帮助,因为它们不倾向于在该位置获取符号。

在代码完成期间是否有直接获取方法参数类型的方法?

编辑:我想做的更好的例子:

namespace app.controller {
    import Controller = sap.ui.core.mvc.Controller;
    export class App extends Controller {
        onInit() {
            this.byId(|)
            console.log("Initializing App Controller");
        }
    }
}

该 |标记代码完成的位置。

【问题讨论】:

    标签: typescript transpiler typescript-compiler-api


    【解决方案1】:

    您需要穿越 AST。请参阅示例脚本。我循环遍历源文件子文件,处理 clases,在 clases 中是方法循环,​​当我找到具有正确名称和参数计数的方法时,我记录第一个参数的类型名称。

    import ts = require("typescript");
    
    var sf = ts.createSourceFile("aaa.ts", "class MyClass { byId(param: sap.ui.core.ID) {} }", ts.ScriptTarget.ES5);
    
    // search all nodes of source file
    sf.forEachChild(function (node: ts.Node) {
    
        // process only classes
        if (node.kind == ts.SyntaxKind.ClassDeclaration) {
    
            // get feautures of ClassDeclarations
            var cls: ts.ClassDeclaration = <ts.ClassDeclaration>node;
    
            // process class childs
            cls.forEachChild(function (m: ts.Node) {
    
                // limit proecssing to methods
                if (m.kind == ts.SyntaxKind.MethodDeclaration) {
                    var method = <ts.MethodDeclaration>m;
    
                    // process the right method with the right count of parameters
                    if (method.name.getText(sf) == "byId" && method.parameters.length == 1) {
                        // get parameter type
                        var type = method.parameters[0].type
    
                        // get raw string of parametr type name
                        var typeName = type.getText(sf);
    
                        // response result
                        console.log("You've got it!" + typeName);
                    }
                }
    
            });
        }
    });
    

    【讨论】:

    • 感谢您的帮助!我明天试试。但是一个问题是,该方法既不必命名为“byId”,也不会只有一个参数。但我将从这个开始并扩展到更复杂的案例。
    • 您必须定义识别此方法的条件。这只是课堂上的一种方法吗?一开始是每次吗?每次都有它的名字吗?如果您可以通过类似的问题(如果打字稿中的关键字)来识别方法,那将非常简单。您还可以检查参数类型名称是否以“sap.ui”或类似名称开头。
    • 我认为问题不是那么小。我用一个例子更新了我的问题。该方法是基类 Controller 上的方法。我从它派生(或从另一个函数使用它等),它应该检查光标位置的参数是否为 sap.ui.core.ID 类型。如果是这样,请转到 xml 文件并搜索 id="bla" 的所有元素。所以它适用于任何使用 sap.ui.core.Id 类型的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2019-05-04
    • 2021-05-13
    • 2020-06-21
    • 1970-01-01
    • 2021-07-10
    • 2020-01-19
    相关资源
    最近更新 更多