Get the type of a prop in a React component in TypeScript

- 5938 views

tldr: Just use the ComponentProps type in React to extract the type of prop of a component.

import CustomComponent from "component-library";
import type { ComponentProps } from "react";
 
type PropType = ComponentProps<typeof CustomComponent>["propName"];

While upgrading this site to Next.js 13.2, I enabled the new Statically Typed Links. But doing this broke some my custom components where the href had to be passed as a prop, as the string type wasn’t enough as the type for the href prop in the Next.js Link component became UrlObject | __next_route_internal_types__.RouteImpl<UrlObject | __next_route_internal_types__.RouteImpl<unknown>>.

So I had to find a way to get exact type the prop in the component, since Next.js didn’t export the type directly. That’s when I came across the ComponentProps type in the React package which can be used to get the types of all the props in a component.

import Link from "next/link";
import type { ComponentProps } from "react";
 
type HrefType = ComponentProps<typeof Link>["href"]; // UrlObject | __next_route_internal_types__.RouteImpl<unknown>

Then it was simple as using that type in my custom components. For example, in my DashboardItem component, this is how I defined the props.

interface DashboardItemProps {
  title: string;
  link:
    | {
        url: ComponentProps<typeof Link>["href"];
        type: "internal";
      }
    | {
        url: string;
        type: "external";
      };
  queryKey: string;
  url: string;
}

You can find the commit on how I did it in my site here.