N
N
Natebash2022-02-17 18:07:42
typescript
Natebash, 2022-02-17 18:07:42

How to properly type this piece of code?

const [showTooltip, setShowTooltip] = useState<boolean>(false); // показывает тултип если true

  const timer = useRef<ReturnType<typeof setTimeout>>();

  const handleMouseEnter = () => {
    timer.current = setTimeout(() => {
      setShowTooltip(true);
    }, 500);
  };

  const handleMouseLeave = () => {
    clearTimeout(timer.current as NodeJS.Timeout);
    setShowTooltip(false);
  };


clearTimeout(timer.current as NodeJS.Timeout); This line is confusing. The question is, how are things like this properly typed?
current - the number of
time when there is no hover effect - undefined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2022-02-17
@Natebash

If you are not using Node.js, then simply exclude the types for it from the TS config.
Then you setTimeoutwill return a simple number, but clearTimeoutwill accept . And no problem.) If for some reason the node code is mixed with the front code, then for front timers you can explicitly write and . number | undefined
window.setTimeoutwindow.clearTimeout

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question