[英]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? 任何人都可以告诉我下面的代码是正确的打字稿或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
If your function expects two functions with no args then it shouldn't be passed functions who expects args. 如果你的函数需要两个没有args的函数,那么就不应该传递期望args的函数。
You can use typescript to check for that: 您可以使用typescript来检查:
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: 然后,如果你有一个args函数,但无论如何你想要传递它,那么你可以使用Function.prototype.bind函数:
function logNumber(num: number): void {
console.log(`this is the number: ${ num }`);
}
myfunction(logNumber.bind(10), () => {});
Typescript is a superset of javascript. Typescript是javascript的超集。 So if it's correct in javascript it sure is correct in typescript;
因此,如果它在javascript中是正确的,那么在typescript中肯定是正确的;
myfunction
is not defined as a function. myfunction
未定义为函数。 It's not valid in javascript. 它在javascript中无效。 It would be valid in typescript if it would pe part of a class.
如果它是一个类的一部分,它将在打字稿中有效。
your code does nothing except evaluating some_condition
. 除了评估
some_condition
之外,你的代码什么都不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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.