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

You can specify a type for the setInterval() function in JavaScript using either of the following:

  1. Using number as the Return Type;
  2. Inferring Type Using ReturnType.

Using number as the Return Type

The JavaScript setInterval() function returns a numeric id for the interval. Therefore, you can simply specify "number" as the return type. For example:

const intervalId: number = setInterval(() => {
    // ...
}, 2000);

Please note that in Node.js, specifying "number" as the return type for setInterval() will throw a "Type 'Timer' is not assignable to type 'number'" error. To fix this error, you can either specify NodeJS.Timeout as the return type or let TypeScript infer the return type of setInterval().

You can also use window.setInterval() instead of setInterval() in a browser environment. In this instance, the function is properly namespaced so TypeScript will automatically infer "number" as its type. For example:

const intervalId = window.setInterval(() => {
    // ...
}, 2000);

This might be useful if you're working in an environment where there is a naming conflict with setInterval() due to some custom or third-party code, as it might help disambiguate which setInterval() function you intend to use.

Inferring Type Using ReturnType

Starting with TypeScript v2.8, you can use the ReturnType utility type to let TypeScript infer the return type of the setInterval() function. For example:

// TypeScript 2.8+
const intervalId: ReturnType<typeof setInterval> = setInterval(() => {
    // ...
}, 2000);

This will construct a type consisting of the return type of the setInterval() function. It's a versatile way to capture the return type of the function without explicitly specifying it.


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.