Skip to content Skip to sidebar Skip to footer

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 N

Solution 1:

Add guard against null:

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

if (timer) {
  clearTimeout(timer);
}

Solution 2:

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


Solution 3:

I got the similar problem and managed to fix it with non-null assertion operator to tell the compiler that "the expression cannot be null or undefined"

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

clearTimeout(timer!);

Post a Comment for "TS2769: How To Fix "clearTimeout" With Return Value From SetTimeout In TypeScript?"