[英]How to create a generic type for an arrow function in Typescript
I try to write typescript functions in the style that is most close to functional. 我尝试以最接近功能的样式编写typescript函数。 For simple functions I can write:
对于简单的函数,我可以写:
type A = (value: number) => string;
const a: A = value => value.toString();
But what can I do with generic types? 但是我可以用泛型类型做什么? How can I type in that simple way following function?
如何以简单的方式输入函数?
function a<T>(value: T): T {
return value;
}
If I try to simply add a generic type, it gives nothing: 如果我尝试简单地添加泛型类型,它什么都不提供:
type A = <T>(value: T) => T;
const a: A = value => value; // `value` implicitly has an `any` type
Is there any way to do it? 有什么办法吗?
In your last snippet: 在你的最后一个片段中:
type A = <T>(value: T) => T;
const a: A = value => value;
You tell the compiler that a
is of type A
, but you don't bind it to a specific generic type which is why it uses any
. 您告诉编译器
a
类型为A
,但是您没有将它绑定到特定的泛型类型,这就是它使用any
。
For example, you can set the generic type like so: 例如,您可以像这样设置泛型类型:
const a: A = (value: string) => value;
You can also do this: 你也可以这样做:
type A<T> = (value: T) => T;
const a: A<string> = value => value;
If you want a
to be specific. 如果你想要
a
是具体的。
If you want a
to stay generic you'll need to declare the generic constraint on it as well: 如果你想要
a
呆在通用就需要申报就可以了通用的限制,以及:
const a: A = <T>(value: T) => value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.