typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:

function identity<T>(arg: T): T {
    return arg;
}

箭头函数的语法是什么?


当前回答

我知道我回答这个问题有点晚了。但我想到了回答这个问题,以防其他人发现它有帮助。没有一个答案提到如何在异步箭头函数中使用泛型。

是这样的:

const example = async <T> (value: T) => {
    //awaiting for some Promise to resolve or reject;
     const result = await randomApi.getData(value);

} 

其他回答

添加多个依赖泛型类型的示例:

这个函数,转换为箭头函数,如下所示:

http.get = function <T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> {
            config.withCredentials = true;
            ....
          };

注意这里的扩展号代替了等号:

http.get = async <T extends any, R extends unknown = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R> => {
            config.withCredentials = true;
            ...
          };

使用<T, extends{}>在试图传递null作为参数时抛出错误。我更喜欢使用<T,>,因为它解决了这个问题。我还不知道原因。但这对我很管用。

这里我有2个带泛型的箭头函数:

直接呼叫:

const foo = <T>(value: T): void => {
    console.log(value);
foo('hello') // hello
}

创建一个稍后使用的类型:

type TFoo<S> = (value: S) => boolean;
const foo: TFoo<number> = (value) => value>0;
console.log(foo(1)) // true
console.log(foo(-1)) // false

希望这对你有所帮助!

如果你在.tsx文件中,你不能只写<T>,但这是可行的:

const foo = <T, >(x: T) => x;

与extends{}攻击不同,这种攻击至少保留了意图。

我喜欢使用这种类型的声明:

const identity: { <T>(arg: T): T } = (arg) => arg;

它允许在需要时为函数定义额外的道具,在某些情况下,它有助于使函数体相对于泛型定义更清晰。

如果你不需要额外的道具(命名空间之类的东西),它可以简化为:

const identity: <T>(arg: T) => T = (arg) => arg;