How do you type React components, hooks and events in TypeScript?
Props
- Type props with a
typeorinterfaceand destructure them:function Card({ title }: CardProps). children: React.ReactNodefor anything renderable.- Avoid
React.FC; plain functions are simpler and support generics. - Extend native element props with
React.ComponentProps<'input'>so...restcan be forwarded. In React 19,refis a normal prop, so noforwardRefis needed.
Hooks
useStateinfers from the initial value; give a type when it starts empty:useState<User | null>(null).useRef<HTMLInputElement>(null)for DOM refs.useReducerinfers from the reducer; type actions as a discriminated union.- Custom hooks returning tuples need
as constto keep tuple types.
Events
React.ChangeEvent<HTMLInputElement>, React.FormEvent<HTMLFormElement>, React.MouseEvent<HTMLButtonElement>. Inline handlers get these types inferred for free.
Example
tsx
type InputProps = React.ComponentProps<'input'> & { label: string };
function TextInput({ label, id, ...rest }: InputProps) {
return (
<label htmlFor={id}>
{label}
<input id={id} {...rest} />
</label>
);
}
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn(v => !v), []);
return [on, toggle] as const; // readonly [boolean, () => void]
}
function Search() {
const [query, setQuery] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setQuery(e.target.value);
return <TextInput label="Search" id="q" ref={inputRef} value={query} onChange={onChange} />;
}Follow-up questions interviewers ask
Try answering each one before you open it.
How do you type a Vue component's props and emits?
With <script setup lang="ts">: const props = defineProps<{ title: string; count?: number }>() and const emit = defineEmits<{ change: [value: number] }>(). Defaults come from destructuring in Vue 3.5 (const { count = 0 } = defineProps<...>()) or withDefaults. vue-tsc type-checks templates as well.