0

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 ?? '';
3
  • 2
    It looks like Ref.current is typed to only accept the value null. So you can't assign Ref.current to be a Timer right now. Can you post how Ref is initialized? If you can fix how Ref is typed such that it is a MutableRefObject<Timer>, then you should be able to assign a Timer to it. Commented Jan 16, 2022 at 15:56
  • this is my code: const Ref = useRef(null); I change it to useRef(MutableRefObject<String>) but not work yet @DavidShortman Commented Jan 16, 2022 at 21:03
  • The value held by useRef may be initialized as null, but you can inform it what type it is expected to be set to by providing a generic: const Ref = useRef<Timer | null>(null); Commented Jan 17, 2022 at 0:11

1 Answer 1

5

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:

// The `current` value is expected to be a `Timer`, and is initialized to `null`
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

Sign up to request clarification or add additional context in comments.

1 Comment

Timer don't work. but useRef<any>(null) work fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.