DEV Community

Maina Wycliffe for This is Learning

Posted on • Originally published at mainawycliffe.dev

5

Looking Up React Components Props Types

In an earlier post, in my All Things Typescript newsletter, we covered how we can look up types for functions in Typescript using the Parameters and ReturnType utility types.

In this short post, I wanted to go a little bit further and look at doing the same for react components. It's a common need for React developers to occasionally create wrappers for third-party components, to customize behavior that's re-usable within their applications.

But from time to time, you will come across third-party libraries that do not export types for their own component props, despite their existence.

What do you do in this case? You could manually annotate the types, but you run the risk of your types getting out of sync with the library's types if the library authors introduce breaking changes.

Fortunately for us, we have a better solution on our hands - the React.ComponentProps utility type. Let's see it in action.

Let's take the following component:

function HelloWorld({ name }: { name: string}) {
  // content of the component here, doesn't matter for the purpose of this article
}
Enter fullscreen mode Exit fullscreen mode

As you can see, the types of props are inlined. Since this is in our control, we can refactor the props types to a reusable Typescript Type, but let's assume we can't and we wanted to re-use the prop types.

This is where React.CompoentProps comes in, and we can use it in combination with the typeof operator to  get the props type, as shown below:

type HelloWorldProps = React.ComponentProps<typeof HelloWorld>;
Enter fullscreen mode Exit fullscreen mode

And in return, we get the following type back:

If you are interested, I wrote about the typeof operator, a while back in my All Things Typescript newsletter, you can find the article here.

And that's it. With a single Utility type - React.ComponentProps, we are able to fetch types from React Components and re-use them within our code with ease, giving us the flexibility to extend components as we need to.

Resources

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay