TypeScript: Generic on an Arrow Function
Overview
With TypeScript, there is risk of <T>
being considered a tag. Therefor when using an arrow function, you need to either provide an trailing comma, a second generic, or an extends.
The Issue
// Possible errors:
// ❌ Cannot find name 'React'.
// ❌ Cannot find name 'T'.
// ❌ JSX element 'T' has no corresponding closing tag.
const test = <T>(value: T) => value;
Solution 1 - Trailing Comma
// ✅
const test = <T,>(value: T) => value;
Solution 2 - Extends Type
// ✅
const test = <T extends object>(value: T) => value;
Solution 3 - Second Type
// ✅
const test = <TValueA, TValueB>(valueA: TValueA, valueB: TValueB) => valueA && valueB;