[英]How to create a generic arrow function with react and typescript
[英]How to create a generic type for an arrow function in Typescript
我尝试以最接近功能的样式编写typescript函数。 对于简单的函数,我可以写:
type A = (value: number) => string;
const a: A = value => value.toString();
但是我可以用泛型类型做什么? 如何以简单的方式输入函数?
function a<T>(value: T): T {
return value;
}
如果我尝试简单地添加泛型类型,它什么都不提供:
type A = <T>(value: T) => T;
const a: A = value => value; // `value` implicitly has an `any` type
有什么办法吗?
在你的最后一个片段中:
type A = <T>(value: T) => T;
const a: A = value => value;
您告诉编译器a
类型为A
,但是您没有将它绑定到特定的泛型类型,这就是它使用any
。
例如,您可以像这样设置泛型类型:
const a: A = (value: string) => value;
你也可以这样做:
type A<T> = (value: T) => T;
const a: A<string> = value => value;
如果你想要a
是具体的。
如果你想要a
呆在通用就需要申报就可以了通用的限制,以及:
const a: A = <T>(value: T) => value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.