Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a simple problem with my TS callbacks.

I have a function like this

...
//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  

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

like image 969
Rainer Plumer Avatar asked Jan 12 '17 22:01

Rainer Plumer


People also ask

How do you pass a callback function in TypeScript?

Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.

Does TypeScript support optional parameter in function?

TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.

How do I declare optional parameters in TypeScript?

In Typescript, making optional parameters is done by appending the “?” at the end of the parameter name in the function when declaring the parameters and the parameters which are not marked with “?” i.e not optional parameter are called as default parameters or normal parameters where it is must and compulsory to pass ...

Can callbacks be anonymous functions?

In JavaScript, callbacks and anonymous functions can be used interchangeably.


1 Answers

This snippet seems to be working fine:

class MyClass {

    public refreshConnection(callback?: Function) {

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

let obj = new MyClass();
obj.refreshConnection(() => { console.log('It works!'); });
like image 170
Uzair Sajid Avatar answered Oct 13 '22 01:10

Uzair Sajid