Search code examples
typescriptgenericsarrow-functions

Error TS2304 when calling generic function inside generic arrow function


Why does Typescript raises an error when I try to call a generic function, from an arrow function using the supplied type parameter.

function a<T>() { }
function b<T>() { a<T>() } // no errors
const c: <T>() => void = () => a<T>() // cannot find name T. ts(2304)

EDIT

This question arose while I was trying to write a generic arrow function similar to c in a .tsx file.

In this case, all of the following syntaxes raises an error.

const c: <T>() => void = <T>() => a<T>()
    //^ Type 'Element' is not assignable to type '<T>() => void'.
       // Type 'Element' provides no match for the signature '<T>(): void'.ts(2322)
const c = <T>() => a<T>() 
         //^ JSX element 'T' has no corresponding closing tag.ts(17008)

In the end, I chose to use the regular function syntax.


Solution

  • Because you declare T in the type definition of c. That is how it should look

    const c: <T>() => void = <T>() => a<T>()