Typed state
TypeScript usually infers simple state from its initial value. An empty array does not contain enough information, so provide the item type explicitly.
TSX
type Task = { id: string; title: string; complete: boolean; }; const [tasks, setTasks] = useState<Task[]>([]); const [title, setTitle] = useState("");
Event types
Inline handlers are inferred from the element. When a handler is named separately, annotate the React event type and the element that produced it.
TSX
function handleChange( event: React.ChangeEvent<HTMLInputElement> ) { setTitle(event.currentTarget.value); } function handleSubmit( event: React.FormEvent<HTMLFormElement> ) { event.preventDefault(); }
Callback props
Describe what the parent expects to receive, not the browser event, when a child reports a meaningful action.
TSX
type TaskFormProps = { onAdd: (title: string) => void; }; function TaskForm({ onAdd }: TaskFormProps) { // The component validates the form, then calls onAdd(title). }
- Type a controlled text input and its change handler.
- Type the form submission handler.
- Add an
onDeletecallback accepting a string id. - Confirm TypeScript rejects a callback with an incompatible parameter.
Extension challenge: create a typed priority select whose state can contain only the three allowed priority values.
Did you know my courses are all printer-friendly? This means you can easily export them to PDF or print them for later use.
