lukehaas / RunJS

RunJS is a JavaScript playground for macOS, Windows and Linux. Write code with instant feedback and access to Node.js and browser APIs.
https://runjs.app
2k stars 43 forks source link

Arrow Function Generics sometimes fail with JSX element 'T' has no closing tag #628

Closed ondrovic closed 2 weeks ago

ondrovic commented 2 weeks ago

Sometimes when writing generic functions they fail. See below for explanation and examples

// this works as expected
function func_UniqueArray <T>(arr: T[]): T[] {
  return Array.from(new Set(arr))
}

const func_result_alpha = func_UniqueArray(['a','a','b','c','c','d'])
const func_result_num = func_UniqueArray([1,1,2,3,3,4,5,5])

console.log(func_result_alpha) //output [ 'a', 'b', 'c', 'd' ]
console.log(func_result_num) //output [ 1, 2, 3, 4, 5 ]
/*
  this should work the same way and does just not in runjs
  it throw's the following complaints
     * JSX element 'T' has no closing tag. Cannot find name 'T'
     * Unexpected token. Did you mean `{'>'}` or `>`?
*/
const arrow_UniqueArray = <T>(arr: T[]): T[] => Array.from(new Set(arr));
const arrow_results_alpha = arrow_UniqueArray(['a','a','a','b','c','c']);
const arrow_results_num = arrow_UniqueArray([1,1,1,1,2,2,3,4,5,6,7,7,7]);

console.log(arrow_results_alpha) //output [ 'a', 'b', 'c' ]
console.log(arrow_results_num) //output [ 1, 2, 3, 4, 5, 6, 7 ]
// however doing this works 
const arrow_UniqueArray = <T,>(arr: T[]): T[] => Array.from(new Set(arr));

const arrow_results_alpha = arrow_UniqueArray(['a','a','a','b','c','c']);
const arrow_results_num = arrow_UniqueArray([1,1,1,1,2,2,3,4,5,6,7,7,7]);

console.log(arrow_results_alpha) //output [ 'a', 'b', 'c' ]
console.log(arrow_results_num) //output [ 1, 2, 3, 4, 5, 6, 7 ]
lukehaas commented 2 weeks ago

A trailing comma is required when writing generics in JSX. This is because the angle brackets will be interpreted as tags otherwise. The same behaviour is present in other editors, such as VS Code.

If you're not intending to write JSX, you can turn it off in the build settings: Screenshot 2024-06-19 at 15 52 50

ondrovic commented 2 weeks ago

That solved it thanks