gpt4 book ai didi

javascript - 似乎无法将函数传递给node.js(TypeScript)中的setTimeout参数数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:17 25 4
gpt4 key购买 nike

这有效:

function test(msg:string){
console.log(msg);
}

setTimeout(test, 1000, ["Hi!"];

...它将打印出“Hi!”一秒钟后到控制台。

这也有效:

function test(){
console.log("Hi!");
}

function callTest(next: () => void){
next();
}

callTest(test);

它还打印出“Hi!”到控制台。

以下结果会导致错误“TypeError: next is not a function”。为什么?

function test(){
console.log("Hi!");
}

function callTest(next: () => void){
next();
}

setTimeout(callTest, 1000, [test]);

对我来说它确实看起来像一个函数!如果第一个代码片段有效,则表明我通常具有正确的形式来使用 setTimeout 并向回调发送参数,而第二个代码片段表明这是调用作为参数传入的函数的正确形式 - 为什么我在第三个代码片段中使用 setTimeout 不起作用?

最佳答案

您只需在传递给 setTimeout 的参数末尾直接传递参数列表即可:

setTimeout(callTest, 1000, test);

如果你有更多的争论,你会这样做:

setTimeout(callTest, 1000, test, a, b, c);

无需像调用 Function.prototype.apply 那样将它们放入数组中。您收到错误的原因是您执行此操作的方式 setTimeout 传递了一个长度为 1 的数组,其中包含对 test 函数的引用。

您之前使用字符串的示例之所以有效,是因为 console.log 完全可以将数组转储到控制台。 TypeScript 没有机会对此提出问题,因为这是 definition of setTimeout当有参数列表传递给将被调用的函数时:

declare function setTimeout(handler: any, timeout?: any, ...args: any[]): number;

如您所见,使用 any 会关闭类型检查。

关于javascript - 似乎无法将函数传递给node.js(TypeScript)中的setTimeout参数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41625424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com