Jan 22, 2022
Per Djurner

TypeScript and functional React components

Here's an example of how I typically add TypeScript types to a functional React component.

import { ReactNode } from "react";

type CmpProps = {
  children: ReactNode;
  classes: string;
};

export function Cmp({ children, classes }: CmpProps): JSX.Element {
  return <div className={classes}>{children}</div>;
}

I prefer this method over using the built-in React.FC type because now I can specify that the children property is required, rather than having it optional as it is in React.FC. This way, if you forget to include the children for the component, TypeScript will scream at you (or if you include children when it should not be included).

Also, note the JSX.Element return type for the function. That can be useful to have in there to catch some silly mistakes made with formatting for example. If you didn't have it specified you would still likely get a TypeScript error somewhere but it would be from where you consume the component instead, which is a little less obvious.

Home