I am working on upgrading some old TypeScript code to use the latest compiler version, and I'm having trouble with a call to setTimeout. The code expects to call the browser's setTimeout function which returns a number:
setTimeout(handler: (...args: any[]) => void, timeout: number): number;
However, the compiler is resolving this to the node implementation instead, which returns a NodeJS.Timer:
setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;
This code does not run in node, but the node typings are getting pulled in as a dependency to something else (not sure what).
How can I instruct the compiler to pick the version of setTimeout that I want?
Here is the code in question:
let n: number;
n = setTimeout(function () { /* snip */ }, 500);
This produces the compiler error:
TS2322: Type 'Timer' is not assignable to type 'number'.
typesdoesn't includenodebutsetTimeoutstill gets its Node type rather than its browser type.typesdefaults to all the types innode_modules/@types, as explained in typescriptlang.org/tsconfig#types, but even if you do specifytypesand don't include"node", why doessetTimeoutstill get its Node type and how can you get the browser type? @Axke's solution is a bit of a hack, basically saying it returns what it returns. TypeScript may still be finding the wrong type, but at least it will be consistently wrong.