javascript - 提供的参数与包装方法中调用目标的任何签名都不匹配 - typescript

标签 javascript 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.

将我的方法传递给另一个方法以使用提供的参数调用它的正确方法是什么?

最佳答案

这是一个常见的错误:您不能将方法函数作为常规函数传递,因为它需要类的实例作为上下文。解决方案是使用闭包:

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/

相关文章:

javascript - 这个 Javascript 事件处理程序参数在哪里定义的?

javascript - 数据表:选择具有给定 ID 的行

javascript - HTML 视频标签在 Safari 浏览器中不起作用

javascript - 为什么 `foo()` 在这里工作?

arrays - 从对象数组中获取值

typescript - 在 router.ts 中访问 Vuex store 模块的状态

c# - 在不访问外部文件的情况下在 WebBrowser 控件中显示图像

angular - PrimeNG Tree - 以编程方式选择 TreeNode

angular - 在 angular 2 中安装 paper.js 和 typings 文件

javascript - 如何在不打开打印机设置页面的情况下在 ionic 应用程序中使用 print.js 进行打印