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

Joh*_*ohn 15 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;
            });
    }
Run Code Online (Sandbox Code Playgroud)

大量的样板,用于单次调用 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;
        });
    }
Run Code Online (Sandbox Code Playgroud)

我可以称之为:

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

但是我收到以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

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

mic*_*urs 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() ); 
Run Code Online (Sandbox Code Playgroud)

有关更完整的示例,您还可以在此处查看我的代码段:http://www.snip2code.com/Snippet/28601/Typescript--passing-a-class-member-funct


Joh*_*ohn 3

我需要包装调用,因此它被包装在一个闭包中,如下所示:

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