简体   繁体   English

如何在Typescript中为箭头函数创建泛型类型

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

相关问题 如何使用 react 和 typescript 创建通用箭头 function - How to create a generic arrow function with react and typescript 使用TypeScript将箭头函数分配给通用函数类型 - Assigning arrow function to generic function type with TypeScript Typescript:箭头的通用功能类型/接口 function - Typescript: generic functional type/interface for arrow function TypeScript 如何为泛型 function 创建泛型类型别名? - TypeScript how to create a generic type alias for a generic function? 如何在 typescript 中同时声明泛型箭头 function 的返回类型为数组和值? - How to declare the return type of a generic arrow function to be an array and value at the same time in typescript? 如何使用Typescript在外部声明的类型创建泛型函数? - How to create a generic function with type declared externally in Typescript? Typescript。如何为以下类型创建通用助手 function? - Typescript. How to create generic helper function for following type? 如何使用 React JSX 在 Typescript 中实现通用箭头 function 作为接口属性 - How to implement a generic arrow function as interface property in Typescript with React JSX TypeScript通用函数的类型 - TypeScript Type of generic function 如何在 function 正文中访问通用 TypeScript 类型? - How to access generic TypeScript type in function body?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM