TypeScript with React

Topic 2 of 3 in TypeScript in practice8 min readIntermediateFree course

Overview

React and TypeScript are the most common pairing in front-end development. Types make components self-documenting: the editor knows every prop, every usage is checked, and refactoring a component’s API shows you every place that needs to change. This lesson covers the patterns you’ll use in every React + TypeScript codebase. (If you’re new to React itself, our React course covers the concepts.)

Setting up

The quickest start is Vite’s React + TypeScript template:

Terminal
npm create vite@latest my-app -- --template react-ts
cd my-app
npm install
npm run dev

It configures jsx: "react-jsx", moduleResolution: "bundler" and noEmit, installs @types/react and @types/react-dom, and runs tsc -b as part of npm run build. Component files use the .tsx extension — TypeScript with JSX.

As usual, Vite only strips types; type errors show in the editor and in the tsc step of the build.

Typing props

Typed React components. type ButtonProps = { label: string; variant?: “primary” | “ghost”; onClick: () => void; }; function Button({ label, variant = “primary”, onClick }: ButtonProps) { return <button className={variant} onClick={onClick}>{label}</button>; }. <Button label="Save" onClick={save} /> is valid. <Button onClick={save} /> fails: Property ‘label’ is missing. <Button label="Hi" variant="big" /> fails: “big” is not a variant. Props are just an object type. Editors autocomplete them, and every usage is checked against the definition. Hooks infer from their initial value: useState(0) is number; use useState<User | null>(null) when it starts empty. Event handlers get exact types: onChange={(e) => …} knows e is React.ChangeEvent<HTMLInputElement>.

A component is a function whose single parameter is its props object, so props are just an object type:

TSX
type ButtonProps = {
  label: string;
  variant?: "primary" | "ghost";
  onClick: () => void;
};

function Button({ label, variant = "primary", onClick }: ButtonProps) {
  return <button className={variant} onClick={onClick}>{label}</button>;
}

<Button label="Save" onClick={save} />;     // ✓
<Button onClick={save} />;
// error TS2741: Property 'label' is missing in type '{ onClick: () => void; }' but required in type 'ButtonProps'.

Destructuring with defaults keeps optional props easy to use. Literal unions ("primary" | "ghost") replace the “magic string” props that cause so many UI bugs. A discriminated union of props can even model components whose props depend on each other — { kind: "link"; href: string } | { kind: "button"; onClick: () => void }.

children

Anything React can render — elements, strings, numbers, arrays, null — is a React.ReactNode:

TSX
import type { ReactNode } from "react";

function Card({ title, children }: { title: string; children: ReactNode }) {
  return (
    <section className="card">
      <h2>{title}</h2>
      {children}
    </section>
  );
}

Events

Inline handlers are typed from context — no annotation needed:

TSX
<input onChange={(e) => setName(e.target.value)} />   // e: ChangeEvent<HTMLInputElement>

When you write the handler as a separate function, use React’s event types:

TSX
import type { ChangeEvent, FormEvent } from "react";

function handleChange(event: ChangeEvent<HTMLInputElement>) {
  setName(event.target.value);
}

function handleSubmit(event: FormEvent<HTMLFormElement>) {
  event.preventDefault();
}

Tip: write the handler inline first, hover over the parameter to see its type, then extract it.

Hooks

useState

useState infers from the initial value:

TSX
const [count, setCount] = useState(0);          // number
const [name, setName] = useState("");           // string
setCount("3");   // ✗ error

When the initial value doesn’t show the full type — typically null or an empty array — pass a type argument:

TSX
const [user, setUser] = useState<User | null>(null);
const [tags, setTags] = useState<string[]>([]);

Then TypeScript makes you handle null before using user — the null and undefined lesson in action.

useRef

TSX
const inputRef = useRef<HTMLInputElement>(null);
// …
inputRef.current?.focus();       // current: HTMLInputElement | null
<input ref={inputRef} />;

useReducer with discriminated unions

For state with several kinds of updates, useReducer plus a discriminated union of actions is a perfect match:

TSX
type Action =
  | { type: "add"; title: string }
  | { type: "toggle"; id: string }
  | { type: "clear-done" };

function tasksReducer(state: Task[], action: Action): Task[] {
  switch (action.type) {
    case "add":        return [...state, { id: crypto.randomUUID(), title: action.title, done: false }];
    case "toggle":     return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
    case "clear-done": return state.filter((t) => !t.done);
  }
}

const [tasks, dispatch] = useReducer(tasksReducer, []);
dispatch({ type: "toggle", id: "1" });   // ✓
dispatch({ type: "toggle" });            // ✗ id is missing

Each action carries exactly the data it needs, and adding a new action type shows you every reducer that must handle it.

Custom hooks

Custom hooks are typed functions. Return an object (or a tuple, typed with as const) so callers get precise types:

TSX
function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = () => setOn((v) => !v);
  return [on, toggle] as const;   // readonly [boolean, () => void]
}

Generic components

Components can be generic, like functions. TypeScript infers the type parameter from the props:

TSX
type ListProps<T> = {
  items: T[];
  getKey: (item: T) => string;
  render: (item: T) => ReactNode;
};

function List<T>({ items, getKey, render }: ListProps<T>) {
  return <ul>{items.map((item) => <li key={getKey(item)}>{render(item)}</li>)}</ul>;
}

<List items={users} getKey={(u) => u.id} render={(u) => u.name} />;   // u: User

Wrapping native elements

To make a component that accepts every prop a native <button> does, plus your own, build on ComponentProps:

TSX
import type { ComponentProps } from "react";

type FancyButtonProps = ComponentProps<"button"> & { variant?: "primary" | "ghost" };

function FancyButton({ variant = "primary", className, ...rest }: FancyButtonProps) {
  return <button className={`btn-${variant} ${className ?? ""}`} {...rest} />;
}

<FancyButton type="submit" disabled onClick={(e) => e.currentTarget.blur()}>Save</FancyButton>;

All the standard attributes — type, disabled, aria-*, event handlers — are typed and autocompleted.

Data from the server

Data fetched in a component is external data: validate it (Validating external data) instead of casting res.json() to your type. Libraries such as TanStack Query and tRPC carry types from the request to the component when paired with a schema.

Remember: props are object types, events have specific types (hover to find them), give useState a type argument when it starts empty, and model reducer actions as a discriminated union.

Exercise

A typed task list

In src/TaskApp.tsx, write: (1) a Badge component with props { tone: "neutral" | "success" | "warning"; children: React.ReactNode }; (2) a reducer tasksReducer(state: Task[], action: Action): Task[] where Action is a discriminated union of add (with title), toggle (with id) and clear-done, using an exhaustive switch; (3) a generic List<T> component with props items: T[], getKey: (item: T) => string and render: (item: T) => React.ReactNode; (4) a TaskApp component using useReducer, a controlled <input> with a typed onChange, and a form onSubmit that dispatches add. Render TaskApp to a string (with renderToStaticMarkup from react-dom/server) after seeding two tasks, and print it, plus the result of running the reducer through a few actions.

TSX
import { useReducer, useState } from "react";
import { renderToStaticMarkup } from "react-dom/server";

type Task = { id: string; title: string; done: boolean };

// 1. Badge

// 2. Action + tasksReducer

// 3. List<T>

// 4. TaskApp

Summary

  • Props are an object type: required, optional (?) and union-typed props are all checked at every usage.
  • Type children as React.ReactNode; event handlers get types like ChangeEvent<HTMLInputElement>.
  • useState infers from its initial value; pass a type argument when it starts empty (useState<User | null>(null)).
  • useReducer with a discriminated-union Action type gives exhaustive, type-safe state updates.
  • Generic components (List<T>) and ComponentProps<"button"> keep reusable components precise.