WillyC
WillyC

Reputation: 4705

Can't seem to pass function to setTimeout argument array in node.js (TypeScript)

This works:

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

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

...in that it will print out "Hi!" to the console after one second.

This also works:

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

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

callTest(test);

In that it also prints out "Hi!" to the console.

The following results in the error "TypeError: next is not a function". Why?

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

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

setTimeout(callTest, 1000, [test]);

It sure looks like a function to me! If the 1st code snippet works it shows that I have the form generally right to use setTimeout and send parameters to the callback, and the 2nd code snippet shows that this is the correct form to call a function passed in as a parameter - why isn't my use of setTimeout in the 3rd code snippet working?

Upvotes: 0

Views: 2635

Answers (1)

Louis
Louis

Reputation: 151401

You just need to pass the list of arguments directly at the end of the arguments you pass to setTimeout:

setTimeout(callTest, 1000, test);

If you had more arguments, you'd do:

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

There's no need to put them in an array like you'd do if you were to call Function.prototype.apply. The reason you are getting an error is that the way you do it setTimeout passes an array of length one that contains a reference to the test function.

The reason your earlier example with the string works is that console.log is absolutely okay with dumping an array to the console. And there's no opportunity for TypeScript to make an issue of it because this is the definition of setTimeout when there's a list of arguments to pass to the function that will be called:

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

As you can see type checking is turned off by the use of any.

Upvotes: 6

Related Questions