CPCODELAB
TypeScript

Typing React Props

9 min read

Typing React Props

When using TypeScript in a React project, you define component props with an interface or type alias, then pass it as a generic to React.FC or annotate the parameter directly. The direct annotation approach is now preferred.

ts
// Preferred: annotate the props parameter directly
interface ButtonProps {
  label: string;
  onClick: () => void;
  disabled?: boolean;
  variant?: "primary" | "secondary" | "danger";
}

export function Button({ label, onClick, disabled = false, variant = "primary" }: ButtonProps) {
  return null; // JSX omitted for brevity
}

// Children
interface CardProps {
  title: string;
  children: React.ReactNode;
}

export function Card({ title, children }: CardProps) {
  return null;
}

For event handlers, React provides typed event types. Always use React.ChangeEvent<HTMLInputElement> for input changes, React.FormEvent<HTMLFormElement> for form submissions, and so on.

ts
function SearchInput() {
  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    console.log(e.target.value);
  }

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

  return null;
}

The @types/react package provides all React type definitions. If you are using a framework like Next.js, these are already set up for you. CPCODELAB projects targeting the web stack come with React types pre-configured.

Ready to test yourself?
Practice TypeScript— quiz & coding exercises