Reputation: 160
I want to use the same variable to store the return value of setInterval()
and then pass it as an argument to clearInterval()
in TypeScript. However, setInterval()
returns NodeJS.Timer
while clearInterval()
takes number
.
This is how I want the code to look like:
itemCooldownInterval: NodeJS.Timer | undefined;
this.itemCooldownInterval = setInterval(this.tickCooldown, 1000);
This is how I want to clear the interval:
clearInterval(this.itemCooldownInterval);
Upvotes: 1
Views: 905
Reputation: 2651
The return values of setInterval in the Browser and Node.js are different. On what platform are you developing?
On the browser the return type is number
. You're IDE might say something different, then just use window.setInterval
instead.
itemCooldownInterval: number | undefined;
// this will work
this.itemCooldownInterval = window.setInterval(this.tickCooldown, 1000);
Either way you can use ReturnType
to infer the matching type:
itemCooldownInterval: ReturnType<typeof setInterval> | undefined;
Upvotes: 1