Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS2769: How to fix "clearTimeout" with return value from setTimeout in TypeScript?

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'.
like image 947
delete Avatar asked Sep 06 '25 03:09

delete


2 Answers

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

like image 106
Md_Zubair Ahmed Avatar answered Sep 07 '25 22:09

Md_Zubair Ahmed


Add guard against null:

let timer: null | ReturnType<typeof setTimeout> = null;
timer = setTimeout( myFunc, 1000 );

if (timer) {
  clearTimeout(timer);
}
like image 33
Miaonster Avatar answered Sep 07 '25 23:09

Miaonster