Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 7.2Typing state, events and forms

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).
}
    
  1. Type a controlled text input and its change handler.
  2. Type the form submission handler.
  3. Add an onDelete callback accepting a string id.
  4. 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.

Feedback 👍
Comments are sent via email to me.