What Is the Correct TypeScript Return Type for JavaScript's setInterval() Function?

Find out what return type should be used for setInterval function in TypeScript

In this article, we'll show you how you can set the correct return type for the setInterval function in JavaScript and Node.js.

Inferring Type Using ReturnType

Without having to know what the return type of setInterval is, we can simply use ReturnType to infer the type in the following way:

const timer: ReturnType<typeof setInterval> = setInterval(() => {
    // do something...
}, 2000);

Using number as the Return Type

Since the return value of setInterval() is a numeric id, specifying the return type as number would work just fine in JavaScript. For example:

const timer: number = setInterval(() => {
    // do something...
}, 2000);

In Node.js, you might encounter the "Type 'Timer' is not assignable to type 'number'" error. This is because in Node.js setInterval() returns a Timer object instead of a numeric id. To work around this, you can either specify Timer as the return type, infer the return type, or use window.setInterval() instead of setInterval() (which will return a numeric id as expected).

Hope you found this post useful. It was published . Please show your love and support by sharing this post.