Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: Cannot invoke an object which is possibly 'undefined' when creating a count up counter

I have the following code for a simple count up counter:

function useInterval(callback: any, delay: any) {
  const savedCallback = useRef();
  savedCallback.current = callback;
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    let id = setInterval(() => {
      savedCallback.current();
    }, delay);
    return () => clearInterval(id);
  }, [delay]);
}

useInterval(() => {
  setTimer(timer + 1);
}, 1000);

While the code works fine, I am getting the following error for this line: savedCallback.current();

Cannot invoke an object which is possibly ‘undefined’.ts(2722)
(property) MutableRefObject.current: undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any ideas on how this can be fixed? Thanks!

>Solution :

callback is of type any so it can be undefined and since

savedCallback.current = callback;

savedCallback.current can be undefined so when you try to invoke it typescript tells that you

Cannot invoke an object which is possibly ‘undefined’.

so what you can do is to give the same type to savedCallback and callback
I guess callback is a function:

function useInterval(callback: () => void, delay: any) {
  const savedCallback = useRef<() => void>(() => {});
  //...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading