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

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

箭头函数的语法是什么?


当前回答

这对我很有用

 const logSomething = <T>(something:T): T => {
       return something;
    }

其他回答

虽然使用extends{}的流行答案是有效的,而且比扩展任何答案都好,但它迫使T成为一个对象

const foo = <T extends {}>(x: T) => x;

为了避免这种情况并保持类型安全,可以使用extends unknown代替

const foo = <T extends unknown>(x: T) => x;

这对我很有用

 const logSomething = <T>(something:T): T => {
       return something;
    }

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

是这样的:

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

} 

非箭头函数的方法。扩展OP中的例子。

function foo<T>(abc: T): T {
    console.log(abc);
    return abc;
}

const x = { abc: 123 };
foo(x);

const y = 123;
foo<number>(y);

除了把整个事情嵌入到一个语句中的答案之外:

const yar = <T,>(abc: T) => {
    console.log(abc);
    return abc;
}

另一种方法是使用中间类型:

type XX = <T>(abc: T) => T;

const bar: XX = (abc) => {
    console.log(abc);
    return abc;
}

操场上

2021年,Ts 4.3.3

const useRequest = <DataType, ErrorType>(url: string): Response<DataType, ErrorType> 
   => {
      ...
   }