TypeScript & React HOCs + Context API
If you ever will struggle with typing HOC in React here are some code snippets that could help you.
Let say you have a simple withTheme
HOC, that provide additional theme
property to your Component.
Now let’s see how we could type this code:
Ok, let’s walk through this code.
Omit
First, we have Omit
type that is really helpful in typing HOCs. Since our HOC is providing theme
prop, if we wrap Component in withTheme
the resulted Component don’t need theme
prop anymore. What Omit
is doing is removing from ones type another’s type keys:
HOC
Then, we’re typing our withTheme
HOC. Let’s see what’s going on here. First of all, I want to say this article is covering this part extensively and I highly recommend reading it: https://medium.com/@jrwebdev/react-higher-order-component-patterns-in-typescript-42278f7590fb The difference here is that my withTheme
HOC injects a new prop and that’s why we need Omit
. This kind of HOCs are useful when dealing with new Context API.
In general, we’re just making sure that we will exclude props that are provided by our HOC from incoming props. It’s worth to notice my HOC is just a function. Let’s see how it would look like, if we would like to type a Class HOC:
HOCs and Context API
As I said earlier, this kind of HOCs are helpful when dealing with Context API. Let’s see how our code might look like if we would like to keep our theme
as a context:
I hope what I showed you here can inspire you to solve some issues you may face in your projects at some point :)
Have a nice day!