簡體   English   中英

TypeScript 可選回調參數與傳遞給它的匿名函數不匹配

[英]TypeScript optional callback parameter does not match anonymous function passed to it

我的 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 的函數調用。 注釋掉可以解決問題

這個片段似乎工作正常:

class MyClass {

    public refreshConnection(callback?: Function) {

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM