While TypeScript is a godsend for React developers, its syntax is fairly intimidating to newcomers. I think generics are a big part of that: they l...
For further actions, you may consider blocking this person and/or reporting abuse
Hey there.
I'm assuming you are learning TS and that's why you don't have a full understand of what generics are or how them work, and why they don't always work when using with React.
I just made a post to explain this a little better, because you have somethings that could be misinterpreted, and cause confusion. I hope you don't mind.
Using Typescript generics with your React components
Michael De Abreu ・ Oct 9 ・ 5 min read
Hey, thanks for engaging with my article.
If I've understood correctly your point you're saying that my section on arrow functions was overly broad and should be restricted to JSX, right?
The syntax that you are using is incorrect, and can't be used. If you try to use it on Typescript Playground it will throw.
Neither of them works. Nor on JSX syntax Link, nor on plain TS syntax Link.
And, your examples of non-working typing, the first one won't work, because you are trying to use generic declaration outside a function scope, but the latter can work without JSX syntax enabled Link
As I mention in the post, using generics in React components is complex, and it won't always work as you may expect. Even with the solution I provide in the example, it requires additional updates in the specific implementation. But, it's great to see that you are having interest in using generics, is a good approach over all.
Ah yeah indeed I made a typo, in both of those cases the equal sign should be before the generyc type. I'll correct the article, thanks for pointing it out.
Ok, it does work now if I move the generic declaration inside the function scope, but still, this doesn't allow me to create a generic functional component:
TS Playground
You can see that this should throw no error, but it does, because we can't use the generic as part of the component typing, because the component typing is outside the function and generic scope. So it does work, but it wouldn't any different than the function declaration component you have at the bottom, and both will have incomplete information about them being actual components. As far TS understand, they both can be used as components because they both recieve props, and return a JSX element, but they don't have all the properties of an actual components.
Thanks for sharing, that hack could be useful when dealing with hooks or hoc.
clear and concise love it sir
Thanks!
What a great article man! Thanks for do it and have shared with us!
Thanks!
Wonderful article. Good explanations and examples.
Hi Matt, I'm glad you liked it! Thanks
Hey all
I'm very happy to be sharing with you my new article. If you have any question, feedback or suggestion on the article, please feel free to tell me!