【问题标题】:Error TS2304 when calling generic function inside generic arrow function在泛型箭头函数中调用泛型函数时出现错误 TS2304
【发布时间】:2020-07-04 10:50:31
【问题描述】:

当我尝试使用提供的类型参数从箭头函数调用泛型函数时,为什么 Typescript 会引发错误。

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

编辑

当我尝试编写通用箭头函数时出现了这个问题 类似于 .tsx 文件中的 c

在这种情况下,以下所有语法都会引发错误。

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)

最后,我选择了使用正则函数语法。

【问题讨论】:

    标签: typescript generics arrow-functions


    【解决方案1】:

    因为您在 c 的类型定义中声明了 T。 应该是这样的

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

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 2018-01-31
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多