简体   繁体   中英

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;
     }
}

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), () => {});

Typescript is a superset of javascript. So if it's correct in javascript it sure is correct in typescript;

  1. myfunction is not defined as a function. It's not valid in javascript. It would be valid in typescript if it would pe part of a class.

  2. your code does nothing except evaluating some_condition . It should either call the callbacks or return them.

This is how I think it would be correct:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM