Menu

TypeScript with React

Lesson 2: TypeScript with React

How do you type React code?

What How
Props type Props = { ... } and function Comp(props: Props)
Children children: React.ReactNode
Events React.ChangeEvent<HTMLInputElement>, React.MouseEvent<HTMLButtonElement>
State useState<CartItem[]>([]) when the initial value is not enough to infer
Refs useRef<HTMLInputElement>(null)
Reducers A discriminated union for actions
Extending HTML elements React.ComponentProps<'button'>

Example

import { useReducer, useRef, useState } from 'react';

type Product = { id: string; name: string; price: number };

type ProductCardProps = {
  product: Product;
  onAdd: (productId: string) => void;
  badge?: React.ReactNode;
};

export function ProductCard({ product, onAdd, badge }: ProductCardProps) {
  return (
    <article>
      <h3>{product.name} {badge}</h3>
      <p>₹{product.price / 100}</p>
      <button onClick={() => onAdd(product.id)}>Add to cart</button>
    </article>
  );
}

// Reducer with a discriminated union of actions
type CartState = { items: Record<string, number> };
type CartAction =
  | { type: 'add'; productId: string }
  | { type: 'remove'; productId: string }
  | { type: 'clear' };

function cartReducer(state: CartState, action: CartAction): CartState {
  switch (action.type) {
    case 'add':
      return { items: { ...state.items, [action.productId]: (state.items[action.productId] ?? 0) + 1 } };
    case 'remove': {
      const { [action.productId]: _, ...rest } = state.items;
      return { items: rest };
    }
    case 'clear':
      return { items: {} };
  }
}

export function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
  const [query, setQuery] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    setQuery(e.target.value);
    onSearch(e.target.value);
  }

  return <input ref={inputRef} value={query} onChange={handleChange} placeholder="Search groceries" />;
}

// Generic component: works for any item type
type ListProps<T> = { items: T[]; getKey: (item: T) => string; render: (item: T) => React.ReactNode };

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

How it works

  • Typing props as a plain function parameter is the recommended style; React.FC is optional and adds little.
  • useState('') infers string. Pass a type argument only when the initial value does not show the full type, such as useState<Product | null>(null).
  • The reducer's switch narrows each action, so action.productId is only available where it exists.
  • List<T> infers T from items, so render receives a fully typed item.

Common mistakes

Mistake Effect Fix
useState(null) for data loaded later Type is stuck as null `useState<Product
Typing events as any No autocomplete for e.target Use React's event types
Re-declaring all button props by hand Missing attributes Extend React.ComponentProps&lt;'button'&gt;

Key takeaways

  • Type props with a type alias, events with React's event types, and state when inference is not enough.
  • Discriminated unions make reducers safe; generics make reusable components.

Try it: Build a typed Button that accepts every normal &lt;button&gt; prop plus a variant: 'primary' | 'secondary' prop.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details