Last updated: Feb 26, 2024
Reading time·2 min
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: