【问题标题】:I am giving the generic type to the function parameter, when i call the function it gives me an error [duplicate]我给函数参数提供了泛型类型,当我调用函数时它给了我一个错误[重复]
【发布时间】:2022-07-21 21:35:19
【问题描述】:

我将泛型类型赋予函数参数,当我调用函数时,它给我一个错误“此表达式不可调用。类型未知没有调用签名”

function a() { return 'abc' }

function fun<T>(x: T, y: string) {
        return x() + y;
    }

fun(a, "str")

【问题讨论】:

  • 您没有指定 T 是可调用类型,因此 Type 'unknown' has no call signatures. 您需要指定 T 可调用 function fun&lt;T extends Function&gt; 或更具体的函数类型(根据需要)。

标签: javascript typescript typescript-generics


【解决方案1】:

正如这个答案https://stackoverflow.com/a/62233415/3262937 中所写,您应该使用T extends Function,以便Typescript 编译器知道您的泛型参数是一个函数。

看看这个游乐场: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAQwBQEpEG9ECcCmUIuSA5MgEYSmIC+AUPaJLAoswDwAqi+AHlHxgAJgGdEAMXDR4YAHyo+ALkRcANIgCeK0VFwwwAc0xZ6icxfMEiJRHwyIA1FoDcZiwybhUyDQCJdXD90IA

【讨论】:

  • 如果答案只是“看到这个其他答案”,那么它应该是作为重复而关闭的投票,而不是答案。 (我认为你是对的,其他问题确实涵盖了这一点,所以很好的发现。)
【解决方案2】:

有办法。

function a() { return 'abc' }

function fun<T>(x: T, y: string) {
        return x + y;
    }

fun(a(), "str");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多