'How do I specify the type of setInterval function in typeScript using React useState() hook?
I have created a timer app using react and typeScript.
In the Project I need to store the instance of setInterval() in useState() hook which I'll use to clear the setInterval() instance.
My timer instance look like this.
const [timer, setTimer] = useState<NodeJS.Timer>();
I'm using this function to clear the timer instance
const stop = () => {
clearInterval(timer);
setTimerOn(false);
};
But the issue with this approach is that inside the stop function clearInterval is showing an error because the type of timer is NodeJS.timer | undefined and only NodeJS.timer type is allowed in clearInterval function.
To remove the undefined type from the useState I have created an dummy setInterval instace and use it as the initial value in useState as shown in the image below.
However I'm wondering whether my approach is correct or it is just a hacky solution? I want to know a proper approach for this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


