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

avatar

Borislav Hadzhiev

Sun Feb 13 20221 min read

banner

Photo by Meiying Ng

The Return Type for setTimeout() in Typescript #

Use the ReturnType utility type to get the return type of the setTimeout method, e.g. const timeout: ReturnType<typeof setTimeout> = setTimeout(). 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);

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>;

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 server or client side.

It should be noted that 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 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.