typescript

What return type should be used for setTimeout in TypeScript?


Consider following code:

const timer: number = setTimeout(() => '', 1000);

Typescript throws an error: Type 'Timer' is not assignable to type 'number'. Quick lookup tells me that setTimeout returns NodeJS.Timer.

But if I am doing browser-based development, using NodeJS.Timer feels wrong. Which is the correct type definition or return type for making setTimeout work without resorting to any declaration?


Solution

  • Simplest solution is to allow type inference to work and not specify any type at all. If you need to specify a type, seeing as the type is not consistent between the browser and node declarations, you could use ReturnType to specify that the type of the variable is whatever the return type of setTimeout is:

    const timer: ReturnType<typeof setTimeout> = setTimeout(() => '', 1000);
    

    Alternately, window.setTimeout can also be used instead of just setTimeout. It returns proper return type.