【问题标题】:How do you use a Typescript Function Interface with a Generic type?你如何使用带有泛型类型的 Typescript 函数接口?
【发布时间】:2021-07-04 01:42:39
【问题描述】:

假设我们有以下函数接口:

interface SomeFunction<T> {(arg: T) :T}

我们可以这样使用界面:

const myFun: SomeFunction<string> = arg => arg;

但问题在于我们将泛型类型T 指定为string。我们怎样才能离开T 通用?

我看到的唯一方法基本上是在函数签名中不使用SomeFunction。像这样:

function myFun2<T>(arg: T): T {
    return arg;
}

但这并不好,因为没有提及SomeFunction接口,即使我们基本匹配它。

有没有更好的方法来声明myFun2,以便我们确保它符合SomeFunction

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    你可以这样声明接口

    interface SomeFunction {
        <T>(arg: T) : T
    }
    

    然后让您完全按照自己的意愿编写函数

    const myFun: SomeFunction = arg => arg
    

    【讨论】:

    • 非常感谢您的回答。它确实回答了我的问题,但现在我有一个跟进。如果我希望能够在我的函数声明中约束泛型类型怎么办。我在这里发布了问题:stackoverflow.com/questions/67001910/…
    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 2022-12-18
    • 2021-07-04
    • 2020-03-24
    • 2021-05-29
    • 2020-01-01
    • 2018-07-03
    • 2021-10-29
    相关资源
    最近更新 更多