DEV Community

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

Collapse
pierreouannes profile image
Pierre Ouannes Author

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 Author

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 on

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.