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

Type 'Timer' is not assignable to type 'null' in typescript

I use this code:

const clearTimer = (e: any) => {
    setTimer(<div></div>);
    if (Ref.current) clearInterval(Ref.current);
    startTimer(e);
    const id = setInterval(() => {
        startTimer(e);
    }, 1000)
    Ref.current = id;
}

For Ref.current = id; I get this error:

(property) MutableRefObject<null>.current: null

Type ‘Timer’ is not assignable to type ‘null’.

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

And these lines not solved my problem:

Ref.current = id.toString();
Ref.current = id ?? '';

>Solution :

When using useRef with Typescript, you should provide a generic argument to specify what is the expected type of the held value.

In your case:

const Ref = useRef<Timer>(null);

Then Ref.current can be assigned to the result of setInterval.

See this article for more info: https://linguinecode.com/post/how-to-use-react-useref-with-typescript

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