DEV Community

Discussion on: React & TypeScript: use generics to improve your types

Collapse
 
michaeljota profile image
Michael De Abreu

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.

Collapse
 
pierreouannes profile image
Pierre Ouannes

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?

Collapse
 
michaeljota profile image
Michael De Abreu

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.

But this doesn't work in TypeScript. Instead, you have to do one of the following:

// use this
const identity<ArgType,> = (arg: ArgType): ArgType => {
  return arg;
}
// or this
const identity<ArgType extends unknown> = (arg: ArgType): ArgType => {
  return arg;
}

I would advise using the first option because it's cleaner, but the comma still looks a bit weird to me.

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.

Thread Thread
 
pierreouannes profile image
Pierre Ouannes

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.

Thread Thread
 
michaeljota profile image
Michael De Abreu • Edited

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.