你如何使用带有泛型类型的 Typescript 函数接口? [英] How do you use a Typescript Function Interface with a Generic type?

查看:28
本文介绍了你如何使用带有泛型类型的 Typescript 函数接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's consider we have the following function interface:

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

我们可以这样使用界面:

We can use the interface like so:

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

但问题是我们将泛型类型 T 指定为 string.我们如何才能让 T 保持通用?

But the issue with that is we specify the generic type T as string. How can we leave T generic?

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

The only way I see how is basically not using SomeFunction in the functions signature. Like so:

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

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

But this is not nice, since there is no mention of the SomeFunction interface even though we basically match it.

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

Is there a better way to declare myFun2 so we make sure it conforms to SomeFunction?

推荐答案

你可以这样声明接口

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

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

which then lets you write your function exactly as you want to

const myFun: SomeFunction = arg => arg

这篇关于你如何使用带有泛型类型的 Typescript 函数接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆