好吧,我猜我错过了一些非常简单的东西。
假设我有多种方法重复很多相同的事情,如下所示:
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.
将我的方法传递给另一个方法以使用提供的参数调用它的正确方法是什么?
最佳答案
这是一个常见的错误:您不能将方法函数作为常规函数传递,因为它需要类的实例作为上下文。解决方案是使用闭包:
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
关于javascript - 提供的参数与包装方法中调用目标的任何签名都不匹配 - typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25631801/