TypeScript with forwardRef
What You'll Learn
You'll learn how to type forwardRef components correctly so TypeScript understands both your props and the element type your ref points to.
The Typing Challenge
When you use forwardRef, TypeScript needs to know two things: what props your component accepts and what type of DOM element the ref will point to. Without proper typing, you'll get cryptic errors or lose autocomplete.
The solution is to use generics with forwardRef. Think of it like filling out a form with two blanks: "This component accepts ___ props and forwards a ref to a ___ element."
The Pattern
Here's the correct TypeScript syntax:
import { forwardRef } from 'react';
interface MyInputProps {
label: string;
placeholder?: string;
}
const MyInput = forwardRef<HTMLInputElement, MyInputProps>(
(props, ref) => {
return (
<div>
<label>{props.label}</label>
<input ref={ref} placeholder={props.placeholder} />
</div>
);
}
);
Notice the two type parameters after forwardRef:
HTMLInputElement– the element type the ref points toMyInputProps– your component's props interface
Now TypeScript knows that ref.current will be an HTMLInputElement, and it will enforce your props interface.
For Other Elements
The element type changes based on what you're forwarding to:
// For a button
forwardRef<HTMLButtonElement, ButtonProps>
// For a div
forwardRef<HTMLDivElement, DivProps>
// For a video element
forwardRef<HTMLVideoElement, VideoProps>
Key Takeaway: Type forwardRef with two generics: the DOM element type first, then your props interface second—this gives you full type safety and autocomplete for both the ref and props.