In "normal" JavaScript, I can do the following:
var timer = setTimeout( myFunc, 1000 );
clearTimout(timer);
But in TypeScript, the setTimeout-Function has a strange return value NodeJS.Timer
, which can't be used for clearTimeout
since clearTimeout requires a number.
How to fix that?
After some research I found the following type-cast:
let timer: null | ReturnType<typeof setTimeout> = null;
timer = setTimeout( myFunc, 1000 );
However, calling
clearTimeout(timer)
via TypeScript gives the following error:
TS2769: No overload matches this call.
Overload 1 of 2, '(timeoutId: Timeout): void', gave the following error.
Argument of type 'Timeout | null' is not assignable to parameter of type 'Timeout'.
Type 'null' is not assignable to type 'Timeout'.
Overload 2 of 2, '(handle?: number | undefined): void', gave the following error.
Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'.
If you are still looking for answer, you need to mention that you are accessing timeouts from window object instead of node
const { setTimeout, clearTimeout } = window
const timerId = setTimeout(() => {
... timeout code here
}, timeoutInMilliSeconds)
// Clear out the timer later
clearTimeout(timerID)
TS playground with window object
Add guard against null:
let timer: null | ReturnType<typeof setTimeout> = null;
timer = setTimeout( myFunc, 1000 );
if (timer) {
clearTimeout(timer);
}
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