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

How to create a generic type for an arrow function in 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;

你告诉编译器 aA 类型,但你没有将它绑定到特定的通用类型,这就是它使用 any.[=19 的原因=]

例如,您可以像这样设置泛型类型:

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;