1

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

2 Answers 2

2

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), () => {});
Sign up to request clarification or add additional context in comments.

4 Comments

but wait, the function completeCallBack or failCallBack are the functions are passed outside. Then who knows they have parameters or not?
Check my revised answer.
your example is not concerned with my case.
What is your case? You asked a pretty general question and so I wrote a general answer. If you have a specific case then edit your question and explain it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.