javascript - TypeScript 可选回调参数与传递给它的匿名函数不匹配

标签 javascript typescript callback signature

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

我有一个这样的功能

...
//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的函数调用。注释掉它可以解决问题

最佳答案

此片段seems to be working很好:

class MyClass {

    public refreshConnection(callback?: Function) {

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

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

关于javascript - TypeScript 可选回调参数与传递给它的匿名函数不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623998/

相关文章:

javascript - 从 Electron 主脚本触发点击

c# - 我如何持续监控新的 TCP 客户端?

c++ - 使用 Windows 消息循环实现回调

javascript - 超基本的 JavaScript 回调

javascript - $ (".class").width($(this)...) 不起作用

javascript - chrome 扩展未捕获 ReferenceError : $ is not defined

javascript - 在javascript中下载深度数据的最佳方法?

javascript - 在 Javascript 中实现 Duck Typing 时,.file() 方法不起作用

javascript - 在 Angular 5 中隐藏 ngFor 的一部分

typescript - 错误 TS2307 : Cannot find module (but it can when running the js)