chipbk10 chipbk10 - 3 months ago 31
TypeScript Question

typescript callback function without parameters?

I want to write some callback functions without parameters.

can anyone tell me below code is correct in typescript or javascript?



myfunction(completeCallBack, failCallBack) {
if (some_condition) {
completeCallBack;
}else {
failCallBack;
}
}

Answer

It should be:

function myfunction(completeCallBack, failCallBack) {
     if (some_condition) {
         completeCallBack();
     } else {
         failCallBack();
     }
}

What you were missing is: ().
If you don't include that then the function won't be executed.

For example:

function fn(): number {
    return 10;
}

let a = fn; // typeof a is () => number
let b = fn(); // typeof b is number

Edit

If your function expects two functions with no args then it shouldn't be passed functions who expects args.
You can use typescript to check for that:

type NoParamsCallback = () => void;

function myfunction(completeCallBack: NoParamsCallback, failCallBack: NoParamsCallback) {
     if (some_condition) {
         completeCallBack();
     } else {
         failCallBack();
     }
}

Then, if you have a function with args but you'd like to pass it anyhow, then you can use the Function.prototype.bind function:

function logNumber(num: number): void {
    console.log(`this is the number: ${ num }`);
}

myfunction(logNumber.bind(10), () => {});