0

我想使用typescript編譯器API獲取類的方法參數類型以提供代碼完成。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"); 
     } 
    } 
} 

的|標記代碼完成的位置。

回答

1

您需要旅行AST。請參閱示例腳本。我遍歷源文件childs,過程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); 
       } 
      } 

     }); 
    } 
}); 
+0

謝謝你的幫忙!我明天會試試。但是一個問題是,該方法不一定會被命名爲「byId」,也不會只有一個參數。但我會從這個開始,並擴展到更復雜的案例。 –

+0

您必須定義識別此方法的條件。這只是課堂上的一種方法嗎?這是否每次都是最初?每次都用「名」來命名?如果您可以通過類似的問題來識別方法(如果打字稿中的關鍵字),它非常簡單。您還可以檢查參數類型名稱是以「sap.ui」還是類似的名字開頭。 – Misaz

+0

我認爲問題不是那麼簡單。我用一個例子更新了我的問題。該方法是基類Controller上的一種方法。我從它派生(或從另一個函數等使用它),它應該檢查光標位置的參數是否爲sap.ui.core.ID類型。如果是這樣,請轉至xml文件並搜索id =「bla」的所有元素。所以它可以使用任何使用sap.ui.core.Id類型的方法。 –