Reputation: 5955
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; } }
Upvotes: 1
Views: 1609
Reputation: 164287
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
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), () => {});
Upvotes: 2
Reputation: 8295
Typescript is a superset of javascript. So if it's correct in javascript it sure is correct in typescript;
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.
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();
}
}
Upvotes: 1