简体   繁体   English

Typescript:箭头的通用功能类型/接口 function

[英]Typescript: generic functional type/interface for arrow function

Ok, I have the following scenario:好的,我有以下场景:

type IHashFn = (arg: string) => number;
const hash: IHashFn = (arg) => {
  return 42;
}

So far, so good.到目前为止,一切都很好。 Now I want the function to be generic.现在我希望 function 是通用的。

const hash: <T> (arg: T) => number = (arg) => {
  return 42;
}

That works.这样可行。 But this doesn't:但这不会:

type IHashFn<T> = (arg: T) => number;
const hash: <T> IHashFn<T> = (arg) => {
  return 42;
}

I found no way to calm down the TS compiler.我发现没有办法让 TS 编译器平静下来。 Using interfaces instead of type aliases doesn't work either.使用接口而不是类型别名也不起作用。

Note: I dont't want hash to be an implementation for IHashFn<string> but generic as well.注意:我不希望hash成为IHashFn<string>的实现,但也是通用的。

Is there a way to declare generic function types or interfaces in TypeScript at all?有没有办法在 TypeScript 中声明通用 function 类型或接口?

You aren't really doing anything with your generic parameter.你并没有真正用你的泛型参数做任何事情。

But it sounds like you want a generic function, not a generic type alias.但听起来你想要一个通用的 function,而不是通用类型别名。 So leave it on the function, and off of the type alias.所以把它留在 function 上,并关闭类型别名。

type IHashFn = <T>(arg: T) => number;

const hash: IHashFn = (arg) => {
  return 42;
}

You can simply use IHashFn<any> .您可以简单地使用IHashFn<any> This will be usable where IHashFn<string> is expected too.这也适用于预期IHashFn<string>的地方。

If you truly want it to still be a generic function type, you could do something like this:如果你真的希望它仍然是一个通用的 function 类型,你可以这样做:

type IHashFn<T = any> = <U extends T>(arg: U) => number;

The solution is to use the built-in Typescript utilities Parameters and ResultType .解决方案是使用内置的 Typescript 实用程序ParametersResultType

For your case:对于您的情况:

type IHashFn<T> = (arg: T) => number;
const hash: <T> (...args: Parameters<IHashFn<T>>) => ResultType<IHashFn<T>> = (arg) => {
  return 42;
}

There might be a cleaner way with the keyword infer used directly, but I could not find it.直接使用关键字infer可能有一种更简洁的方法,但我找不到。 Maybe someone else can add it here.也许其他人可以在这里添加它。

I had the same question and it was impossible to find a solution for me, I had to learn about the existence of these utilities and figure it out by myself.我有同样的问题,无法为我找到解决方案,我必须了解这些实用程序的存在并自己解决。

In my case, I wanted to take advantage of the existing React.FunctionComponent (or React.FC ) type alias, while using a generic.就我而言,我想利用现有的React.FunctionComponent (或React.FC )类型别名,同时使用泛型。

List of utility types:https://www.typescriptlang.org/docs/handbook/utility-types.html实用程序类型列表:https://www.typescriptlang.org/docs/handbook/utility-types.html

More info on infer: https://blog.logrocket.com/understanding-infer-typescript/有关推断的更多信息: https://blog.logrocket.com/understanding-infer-typescript/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM