CodePark/ questions / TypeScript with React
START PRACTICINGPRACTICE
Frontend question · TypeScript › TypeScript with React

How do you type a React component's props, including children? What about React.FC?

type CardProps = {
  title: string;
  variant?: "primary" | "ghost";
  children: React.ReactNode;
};

function Card({ title, variant = "primary", children }: CardProps) {
  return <section className={variant}><h2>{title}</h2>{children}</section>;
}

Declare a type or interface for the props and annotate the destructured parameter. Type children as React.ReactNode. React.FC also works, but plain functions are now more common.

  • Optional props use ? and get default values in the destructuring, like variant = "primary".
  • Either type or interface works. Pick one convention.

React.ReactNode covers everything React can render: elements, strings, numbers, arrays, null and so on. If a component must receive children, make the prop required. If not, add ?.

React.FC<Props> also works. Since the React 18 types, it no longer adds children for you, so you declare children either way.

Many codebases now prefer plain function declarations with typed props. They read like normal functions and work naturally with generics. But this is a style choice.

  • Write props as a type or interface, and annotate the function parameter.
  • Mark optional props with ? and give them defaults in the destructuring.
  • Type children as React.ReactNode.
  • Since the React 18 types, React.FC no longer adds children for you.
  • Plain functions are common, and they are simpler with generics.