patterntypescriptCritical
What return type should be used for setTimeout in TypeScript?
Viewed 0 times
whatsettimeouttypeusedreturnshouldfortypescript
Problem
Consider following code:
Typescript throws an error:
But if I am doing browser-based development, using
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
Alternately,
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.