本文介绍了TypeScript可选回调参数与传递给它的匿名函数不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的TS回调有一个简单的问题。

I have a simple problem with my TS callbacks.

我有这样的函数

...
//inside a class
    //function is supposed to optionally accept any callback function
    refreshConnection(callback?:Function) {
        //do something
        //then call the passed callback with no params
        callback();
    }

...

//in another component, i call this function like so
this.myclass.refreshConnection( () => {
    window.location.reload();
});

//but i get an error saying that the function parameter does not match a signature.

// i also tried callback?: (...args: any[]) => any but nothing.


ERROR in ./src/app/fb_connect.component.ts
Module build failed: Error: /var/www/mysite/frontend/angular2/src/app/fb_connect.component.ts (70,41): Supplied parameters do not match any signature of call target.)
    at _checkDiagnostics (/var/www/mysite/frontend/angular2/node_modules/@ngtools/webpack/src/loader.js:115:15)
    at /var/www/mysite/frontend/angular2/node_modules/@ngtools/webpack/src/loader.js:140:17
 @ ./src/app/app.module.ts 15:0-51
 @ ./src/app/index.ts
 @ ./src/main.ts

注意:(70,41)是refreshConnection的函数调用。将其注释掉即可解决问题

Note: (70,41) is the function call for refreshConnection. Commenting it out fixes the problem

推荐答案

此代码段罚款:

class MyClass {

    public refreshConnection(callback?: Function) {

        if (callback) {
            callback();
        }
    }
}

let obj = new MyClass();
obj.refreshConnection(() => { console.log('It works!'); });

这篇关于TypeScript可选回调参数与传递给它的匿名函数不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 18:04