Write your own 'PropsFrom' helper to extract props from any React component

Type helpers change the game when it comes to types in your codebase. They help TypeScript infer more from your code - and make your types a lot more readable. Here, I write my own PropsFrom helper to extract props from any React component.

Discuss on Twitter

Transcript

A common pattern in TypeScript is to create type helpers that allow you to extract types from things that are not types. Here, we've created a PropsFrom type helper which extracts a component, if I call this TComponent here. Currently, what we wanted to do is we want it to return the props. Here, it would return enabled boolean if we put my components in there. Let's see how we do that.

If we go TComponent extends React.FC, which is a functional component, then we can actually add a generic there. We can say infer the props and then we can return the props. Otherwise, because this is a ternary, it needs to return something, we say never.

Now, PropsFrom, this is going to return enabled boolean because, if I change this up here to a, for instance, just say it's true and I had false here, then that's going to fail because it's expecting true. What if you want to be able to feed in two different types of things into this helper? Then you need to add an extra layer to the ternary.

Let's imagine that we had a MyOtherComponents here, because React components can be added as classes, too. Here, what we do is we say instead of this, TComponent extends React.Component, then we return Props, and then we have never.

Now, we can say PropsFrom is basically like...Why is this not working? Boolean is not returned, so never, so we can say Components instead. This now is working both with React functional components, which you see here, and with react components declared as classes.

More Tips