Lesson 3 of 9 · 19m
Events, Forms, and Trusting Inference
Type DOM events accurately, use generics in form handlers sparingly, and let TypeScript infer what it already knows.
Typed React code often fails in the boring places: event becomes any, a form handler lies about its input type, or someone annotates everything until the inference engine might as well not exist. The goal is precision at the boundary and silence everywhere else.
Let JSX infer common event types
function SearchBox() {
return (
<input
name="q"
onChange={(event) => {
console.log(event.currentTarget.value); // inferred ChangeEvent<HTMLInputElement>
}}
/>
);
}When the handler is inline, TypeScript knows the element and infers the event. Extract the handler and now you annotate it:
function handleSearchChange(event: React.ChangeEvent<HTMLInputElement>) {
console.log(event.currentTarget.value);
}Use currentTarget for the element the handler is attached to. target is the element that originated the event, which may be a child.
FormData is strings until proven otherwise
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const data = new FormData(event.currentTarget);
const email = data.get("email");
if (typeof email !== "string" || email.length === 0) {
throw new Error("Email is required");
}
}FormData.get() returns FormDataEntryValue | null — a string or File, possibly absent. Validate before narrowing. Types do not make user input trustworthy; they make the untrustworthiness visible.
Keyboard events need the right element type
function handleKeyDown(event: React.KeyboardEvent<HTMLTextAreaElement>) {
if ((event.metaKey || event.ctrlKey) && event.key === "Enter") {
event.currentTarget.form?.requestSubmit();
}
}The generic parameter matters because currentTarget changes with the element. KeyboardEvent alone defaults too loosely and hides useful element-specific properties.
Annotation discipline
// noisy and usually unnecessary
const [open, setOpen] = useState<boolean>(false);
// necessary when inference cannot know the full domain
const [selectedId, setSelectedId] = useState<string | null>(null);Annotate when the initial value is narrower than the legal state. Otherwise inference is clearer and refactors better.
Field notes
React.MouseEventis not the DOMMouseEvent; they are different types.- Do not write
event: anyto silence a mismatch — find the actual element type. - Validate form data at the boundary, then pass narrowed values deeper.
strictNullChecksturns most form mistakes into compile-time errors; turning it off is borrowing pain at high interest.
Was this lesson helpful?