'How to use generics with arrow functions in Typescript/JSX with React?
Using Typescript, typing in Visual Studio, into a ".ts" file, consider the following declaration:
export const foo = <T>(myObject: T) => myObject.toString();
This works fine, type checking is fine, everything is great.
Now place that exact same code into a ".tsx" file that is being used for JSX and React.
Intellisense gets very upset and complains, because it is trying to make the <T> into a React JSX element. But my intention is to have the compiler treat it as a generic type designator.
The compiler complains with:
[gulp-typescript] 17008 JSX element 'T' has no corresponding closing tag.
I have tried numerous syntactical workarounds to try to get both the IDE and the compiler to let me escape the JSX and force the <T> to be understood by the compiler as a generic, as it would if JSX is not in use. But I can't find the magic sauce to do this.
Anyone smarter than I out there who can figure this out?
Solution 1:[1]
The usual workaround is to add a trailing comma:
export const foo = <T,>(myObject: T) => myObject.toString();
Solution 2:[2]
I personally use extends unknown. Sounds safest to me
const foo = <T extends unknown>(myObject: T) => myObject.toString();
Solution 3:[3]
I can't think of a way around that, and will be glad as you to learn of one.
However, here's a different way to achieve the same:
export const foo = function<T>(myObject: T) { return myObject.toString(); }
The compiler won't complain about the generics.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Petur Subev |
| Solution 3 | Nitzan Tomer |
