HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptCritical

What return type should be used for setTimeout in TypeScript?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whatsettimeouttypeusedreturnshouldfortypescript

Problem

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 = setTimeout(() => '', 1000);


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

Code Snippets

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

Context

Stack Overflow Q#51040703, score: 472

Revisions (0)

No revisions yet.