Home > Software design >  Type 'Timer' is not assignable to type 'null' in typescript
Type 'Timer' is not assignable to type 'null' in typescript

Time:01-21

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'.

And these lines not solved my problem:

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

CodePudding user response:

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

  •  Tags:  
  • Related