简体   繁体   English

如何使用具有通用类型的 Typescript Function 接口?

[英]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.

相关问题 如何在 Typescript Function 接口中约束通用类型? - How do you constrain a Generic type in a Typescript Function Interface? 如何为接口使用泛型类型 - TypeScript? - How to use generic type for interface - TypeScript? 如何在接口中使用 typescript 泛型类型? - How to use typescript generic type in interface? 如何指定使用Typescript道具接口的类函数 - how do you specify a class function to use typescript props interface 如何为具有扩展接口的泛型类型的函数参数做 TypeScript tsdoc 文档? - How to do TypeScript tsdoc documentation for function argument with generic type that extends an interface? Typescript 如何扩展使用泛型类型的接口? - Typescript how do I extend an interface which uses a generic type? 如何正确使用 Typescript 中的 React.lazy() 来导入带有泛型类型参数的反应组件? - How do you correctly use React.lazy() in Typescript to import a react component with a generic type parameter? Typescript - 使用基接口作为泛型类型 - Typescript - Use base interface as generic type Typescript:箭头的通用功能类型/接口 function - Typescript: generic functional type/interface for arrow function 如何在 Typescript 中键入泛型类型作为接口的子集? - How to type a generic type as a subset of an interface in Typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM