How to use TypeScript with React

· Category: TypeScript

Short answer

TypeScript integrates with React through type definitions for JSX, component props, state, and hooks, providing compile-time checks for your UI layer.

Steps

  1. Create a functional component with typed props:
interface ButtonProps { label: string; onClick: () => void; }
const Button: React.FC<ButtonProps> = ({ label, onClick }) => ...
  1. Type useState: const [count, setCount] = useState<number>(0);
  2. Type event handlers: const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => ...
  3. Type refs with useRef<HTMLInputElement>(null).
  4. Use generic components for reusable lists and tables.

Tips

  • Use React.ComponentProps to extract prop types from HTML elements or third-party components.
  • Prefer explicit return types on public components for clearer error messages.

Common issues

  • Children prop typing can be tricky; use React.ReactNode for maximum flexibility.
  • Event types vary by element; using the wrong one causes subtle type mismatches.