Skip to content

QuizNot attempted

A ref that stores a timer id

You keep an interval id in a ref so a Stop button can clear it. Which declaration type-checks in a project that also has @types/node installed?
const timerRef = useRef</* ? */>(null);
timerRef.current = setInterval(tick, 1000);
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • useRef<ReturnType<typeof setInterval> | null>(null)
  • With @types/node loaded, the global setInterval returns NodeJS.Timeout rather than number, so ReturnType<typeof setInterval> stays correct whichever typings win (calling window.setInterval explicitly also gives number).
  • The ref is mutable data, not a DOM node, so assigning to current is the whole point.
  • Not number | null: fails as soon as Node's typings shadow the DOM ones.
  • Not HTMLElement | null: a timer id is not a DOM node.
  • Not null: the ref could then only ever hold null.