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

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

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

Inferring Type Using ReturnType

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

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

Using number as the Return Type

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

const timer: number = setTimeout(() => {
    // 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 setTimeout() 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.setTimeout() instead of setTimeout() (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.