setTimeout it returns a type of number . Show activity on this post.
Return valueThe returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout() . This value can be passed to clearTimeout() to cancel the timeout.
Category: Control. Clears an existing timer by passing in the numeric value returned by setTimeout(). Sometimes you need to clear a timeout timer before it executes. clearTimeout() uses the value returned by the setTimeout(function, milliseconds) function.
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.
You can use window.setTimeout
it returns a type of number
.
let a: number;
a = window.setTimeout(function() {}, 0);
This happens because Typescript will search for all type definitions under node_modules/@types
If you installed NodeJS type definition (comes with many npm packages) into ~/node_modules/@types/node/globals.ts
and your project is in ~/Projects/myproject
, the NodeJS definitions for setTimeout
will leak.
By default all visible “@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible; specifically, that means packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so on.
See: https://www.typescriptlang.org/tsconfig#types
If Typescript finds custom type definitions its is prioritized over the default type definitions.
Solutions:
"typeRoots":[]
"types": []
window.setTimeout()
insteadwindow.setTimeout
returns number
. Ideally, you want to define your own type to distinguish it from number (and prevent some ops like +
which don't make sense for timers).
type TimerHandle = number;
For anyone else having this error what worked for me is adding in the tsconfig.js file:
"compilerOptions": {
...
"types": [],
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With