Generics in React TSX Files

Viewed 216

This might be a simple question but can't find the answer for it online. In a ts file I can define a function like this:

const lastGeneric = <T>(arr: Array<T>): T => { 
   return arr[arr.length - 1];
}

However, if I attempt to do this in a tsx file, I receive a bunch of syntax errors, as it assumes I'm trying to create JSX with a component called T

enter image description here

Is there an alternative way of defining the above function in a tsx file? What am I doing wrong?

2 Answers

Just add extra comma after T generic:

const lastGeneric = <T,>(arr: Array<T>): T => { 
   return arr[arr.length - 1];
}

My answer probably is a duplicate. Feel free to flag it. I just cant find the original one.

This issue occurs because of jsx. TS is unsure how to parse angle brackets

Apart from captain's solution, you can define your generic types in a type statement where JSX won't be parsed:

type SomeFunc = <T>(arr: Array<T>) => T;

const lastGeneric: SomeFunc = arr => { 
   return arr[arr.length - 1];
}
Related