#Why Does This Happen?
In Node.js, when you use the setTimeout()
or setInterval()
timer functions, they return a Timeout
object, which is different from the numeric IDs returned by the browser's timer functions. Therefore, trying to assign the return value of setTimeout()
or setInterval()
to a variable with the type "number
" will result in the following TypeScript error:
// Error: Type 'Timeout' is not assignable to type 'number'.
const timeoutId: number = setTimeout(() => {
// ...
}, 2000);
// Error: Type 'Timeout' is not assignable to type 'number'.
const timeoutId: number = setInterval(() => {
// ...
}, 2000);
#How to Fix the Issue?
To fix this issue you can do either of the following:
-
Specify
NodeJS.Timeout
as the return type ofsetTimeout()
:const timeoutId: NodeJS.Timeout = setTimeout(() => { // ... }, 2000);
const timeoutId: NodeJS.Timeout = setInterval(() => { // ... }, 2000);
-
Infer the return type of timer function using the TypeScript
ReturnType
utility type:const timeoutId: ReturnType<typeof setTimeout> = setTimeout(() => { // ... }, 2000);
const timeoutId: ReturnType<typeof setInterval> = setInterval(() => { // ... }, 2000);
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.