How do you write a generic arrow function in a .tsx file?
In .tsx, <T>(x: T) => x is parsed as a JSX tag and fails. Write <T,>(x: T) => x with a trailing comma, or <T extends unknown>, or use a regular function declaration instead.
Explain it simply
In a .tsx file the compiler has to decide whether <T> opens a JSX tag like <div> or starts a type parameter list. With a lone <T> it picks JSX, so you get a confusing error.
The fix is to make it clear it cannot be a tag. A trailing comma, <T,>, does this and is the usual trick. <T extends unknown> also works. Or sidestep it by declaring the function with the function keyword.
Example
// In a .ts file this is fine:
// const wrap = <T>(x: T) => [x];
// In a .tsx file use one of these:
const wrap = <T,>(x: T): T[] => [x];
const wrap2 = <T extends unknown>(x: T): T[] => [x];
function wrap3<T>(x: T): T[] {
return [x];
}
const nums = wrap(5); // number[]
const names = wrap3("Asha"); // string[]What to say in the interview
"The generic arrow syntax <T>(x) clashes with JSX in .tsx files. I add a trailing comma, <T,>, or a dummy constraint, or just use a function declaration."