2014-09-02 29 views
15

好吧,我猜我錯過了一件非常簡單的事情。提供的參數與包裝方法中調用目標的任何簽名都不匹配 - Typescript

比方說我有重複了很多相同的東西像這樣多種方法:樣板

public getDepartments(id: number): ng.IPromise<IDepartmentViewModel[]> { 
     this.common.loadStart(); 
     return this.unitOfWork.teamRepository.getDepartmentsForTeam(id).then((response: IDepartmentViewModel[]) => { 
      this.common.loadComplete(); 
      return response; 
     }).catch((error) => { 
       this.common.loadReset(); 
       return error; 
      }); 
    } 

噸至this.unitOfWork.teamRepository.getDepartmentsForTeam(id)

一個電話,所以我想爲一個通用的包裝樣板如:

private internalCall<T>(method:() => ng.IPromise<T>): ng.IPromise<T> { 
     this.common.loadStart(); 
     return method().then((response: T) => { 
      this.common.loadComplete(); 
      return response; 
     }).catch((error) => { 
      this.common.loadReset(); 
      return error; 
     }); 
    } 

,我可以再調用,如:

public getDepartments(id: number): ng.IPromise<IDepartmentViewModel[]> { 
     return this.internalCall<IDepartmentViewModel[]>(this.unitOfWork.teamRepository.getDepartmentsForTeam(id)); 

,但我得到了以下錯誤:

Supplied parameters do not match any signature of call target: 
Type '() => ng.IPromise<IDepartmentViewModel[]>' requires a call signature, but type 'ng.IPromise<IDepartmentViewModel[]>' lacks one. 

什麼是通過我的方法到其他與提供的參數來調用它的正確方法?

回答

3

我需要換行調用,這樣它被包裹在一個閉包像這樣:

public getDepartments(id: number): ng.IPromise<IDepartmentViewModel[]> { 
    return this.internalCall<IDepartmentViewModel[]>(
     () => { return this.unitOfWork.teamRepository.getDepartmentsForTeam(id); } // Wrapping here too 
    ); 
18

這是一個常見的錯誤:你不能傳遞的方法功能作爲常規功能,因爲它需要的實例類作爲上下文。該解決方案是使用封閉:

function foo(func:() => any) { 
} 
class A { 
method() : any { 
} 
} 
var instanceOfA = new A; 

// Error: you need a closure to preserve the reference to instanceOfA 
foo(instanceOfA.method); 
// Correct: the closure preserves the binding to instanceOfA 
foo(() => instanceOfA.method()); 

更完整的例子中,你還可以看到我的snippet發表在這裏:http://www.snip2code.com/Snippet/28601/Typescript--passing-a-class-member-funct

1

僅適用於文檔 - 我得到這個錯誤時,我不小心叫錯(現有)函數具有錯誤的參數。必須查看打包文件.tmp/bla/bla/bla.ts中的錯誤行以查看錯誤。

0

嘗試將您的胖箭頭替換爲正常功能。這將解決問題。 ()=> ng.IPromise 到 功能(){ng.IPromise .....}

0

在我來說,一個簡單的伎倆讓我躲閃的錯誤。呼叫(或觸發)功能的是由於它括號,這樣:

class MyClass { 
foo: any; 

    firstMethod() { 
    this.foo = this.secondMethod; 
    this.foo(); 
    } 

    secondMethod() { 
    } 
} 
0

在一個更通用的答案,錯誤「提供的參數不包裝方法匹配通話對象的任何簽名 - Typescript「指出您正在調用具有錯誤參數的函數。

例如()接收每個定義的兩個參數,但僅一個傳遞:

example('param1') // wrong 
example('param1','param2') // OK! 
相關問題