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

You can specify a type for the setTimeout() 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 setTimeout() function returns a numeric id for the timeout. Therefore, you can simply specify "number" as the return type. For example:

const timeoutId: number = setTimeout(() => {
    // ...
}, 2000);

Please note that in Node.js, specifying "number" as the return type for setTimeout() 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 setTimeout().

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

const timeoutId = window.setTimeout(() => {
    // ...
}, 2000);

This might be useful if you're working in an environment where there is a naming conflict with setTimeout() due to some custom or third-party code, as it might help disambiguate which setTimeout() 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 setTimeout() function. For example:

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

This will construct a type consisting of the return type of the setTimeout() 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.