Typing arrow functions in TSX

JSX in Typescript (i.e. TSX) has an ambiguous grammar which can cause problems in you code.

If you are using an arrow function and want to use a type variable in it, it’s going to mistake the generic syntax eg. <T> for HTML and will not compile.

const foo = <T>(x: T) => x;

If you look for a solution to this on the internet you’re likely to come across this weird syntax which in my opinion completely obscures what you are trying to achieve.

const foo = <T extends {}>(x: T) => x;

Far neater and to the point is this

const foo = <T,>(x: T) => x;

The comma lets the parser know that it’s looking at a type variable and not HTML.

Leave a comment