Back to TIL
June 2025
posted on 06.05.2025

TypeScript: ElementRef for React.useRef

You can extract the type from a useRef hook using ElementRef:

import { useRef, ElementRef } from "react";
 
const Component = () => {
  const audioRef = useRef<ElementRef<"audio">>(null);
//       ^? React.RefObject<HTMLAudioElement>

  return <audio ref={audioRef}>Hello</audio>;
};

Read Matt Pocock's Strongly Type useRef with ElementRef.

No reactions yet

in Naperville, IL
Last visitor from Mitaka, Japan