[英]How do you use a Typescript Function Interface with a Generic type?
Let's consider we have the following function interface:假设我们有以下 function 接口:
interface SomeFunction<T> {(arg: T) :T}
We can use the interface like so:我们可以像这样使用接口:
const myFun: SomeFunction<string> = arg => arg;
But the issue with that is we specify the generic type T
as string
.但问题是我们将泛型类型
T
指定为string
。 How can we leave T
generic?我们怎样才能让
T
通用?
The only way I see how is basically not using SomeFunction
in the functions signature.我看到的唯一方法基本上是不在函数签名中使用
SomeFunction
。 Like so:像这样:
function myFun2<T>(arg: T): T {
return arg;
}
But this is not nice, since there is no mention of the SomeFunction
interface even though we basically match it.但这并不好,因为没有提到
SomeFunction
接口,即使我们基本上匹配它。
Is there a better way to declare myFun2
so we make sure it conforms to SomeFunction
?有没有更好的方法来声明
myFun2
以确保它符合SomeFunction
?
You can declare the interface like this您可以像这样声明接口
interface SomeFunction {
<T>(arg: T) : T
}
which then lets you write your function exactly as you want to然后,您可以完全按照自己的意愿编写 function
const myFun: SomeFunction = arg => arg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.