What's the Return Type for setTimeout() in Typescript

avatar
Borislav Hadzhiev

Last updated: Feb 26, 2024
2 min

banner

# The Return Type for setTimeout() in Typescript

Use the ReturnType utility type to get the return type of the setTimeout method.

The ReturnType utility type constructs a type that consists of the function's return type.

index.ts
const timeout: ReturnType<typeof setTimeout> = setTimeout(() => { console.log('success'); }, 1500); console.log(timeout);

return type for set timeout function

The code for this article is available on GitHub

The ReturnType utility type allows us to construct a type that consists of the return type of the passed-in function.

index.ts
function sum(a: number, b: number) { return a + b; } // 👇️ type T = number type T = ReturnType<typeof sum>;

using return type utility type

This approach is needed because the return type of the setTimeout method is NodeJS.Timeout in Node and number in the browser.

By using the ReturnType utility type, we are able to get the correct return type of the setTimeout method regardless if writing code on the server or the client side.

Even though the return type of the setTimeout method is different between Node.js and the browser, the return value is used in the same way.

It is passed to the clearTimeout() method to cancel the timeout if necessary.

index.ts
const timeout: ReturnType<typeof setTimeout> = setTimeout(() => { console.log('success'); }, 1500); clearTimeout(timeout);
The code for this article is available on GitHub

The clearTimeout method takes a number or a NodeJS.Timeout object as a parameter (depending on the environment), so you can directly pass the timeout value to the method.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.