TypeScript in Practice

TypeScript in real projects · Lesson 7 of 12 · 18 min

Typing React components and hooks

Most React typing comes down to props, state and events. Here are the patterns that cover 95% of components.

Props

type ButtonProps = React.ComponentProps<"button"> & {
  variant?: "primary" | "ghost";
};
 
export function Button({ variant = "primary", ...props }: ButtonProps) {
  return <button data-variant={variant} {...props} />;
}

Extending React.ComponentProps<"button"> gives you onClick, disabled, type and every other native prop for free.

State and events

const [user, setUser] = useState<User | null>(null);
 
function onChange(e: React.ChangeEvent<HTMLInputElement>) {
  setQuery(e.target.value);
}

Context without undefined checks everywhere

const CartContext = createContext<Cart | null>(null);
 
export function useCart() {
  const cart = useContext(CartContext);
  if (!cart) throw new Error("useCart must be used inside <CartProvider>");
  return cart; // Cart, not Cart | null
}

Exercise: type the <Select> component in the starter project so onChange receives the option's value type, not string.