Wil*_*lyC 0 javascript settimeout node.js typescript
这有效:
function test(msg:string){
console.log(msg);
}
setTimeout(test, 1000, ["Hi!"];
Run Code Online (Sandbox Code Playgroud)
...它会打印出“嗨!” 一秒钟后到控制台。
这也有效:
function test(){
console.log("Hi!");
}
function callTest(next: () => void){
next();
}
callTest(test);
Run Code Online (Sandbox Code Playgroud)
它还打印出“Hi!” 到控制台。
以下结果会导致错误“TypeError:next 不是函数”。为什么?
function test(){
console.log("Hi!");
}
function callTest(next: () => void){
next();
}
setTimeout(callTest, 1000, [test]);
Run Code Online (Sandbox Code Playgroud)
对我来说它确实看起来像一个函数!如果第一个代码片段有效,则表明我通常具有正确的形式来使用 setTimeout 并向回调发送参数,而第二个代码片段表明这是调用作为参数传入的函数的正确形式 - 为什么不'我在第三个代码片段中使用 setTimeout 有效吗?
您只需在传递给的参数末尾直接传递参数列表setTimeout:
setTimeout(callTest, 1000, test);
Run Code Online (Sandbox Code Playgroud)
如果你有更多的争论,你会这样做:
setTimeout(callTest, 1000, test, a, b, c);
Run Code Online (Sandbox Code Playgroud)
无需像调用 那样将它们放入数组中Function.prototype.apply。您收到错误的原因是您执行此操作的方式setTimeout传递了一个长度为 1 的数组,其中包含对该函数的引用test。
您之前使用字符串的示例之所以有效,是因为console.log将数组转储到控制台绝对没问题。TypeScript 没有机会对此提出问题,因为这是何时将参数列表传递给将被调用的函数的定义:setTimeout
declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,类型检查通过使用 被关闭any。