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

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

箭头函数的语法是什么?


当前回答

这么晚了,但与ES6不需要扩展它仍然为我工作....:)

let getArray = <T>(items: T[]): T[] => {
    return new Array<T>().concat(items)
}

let myNumArr = getArray<number>([100, 200, 300]);
let myStrArr = getArray<string>(["Hello", "World"]);
myNumArr.push(1)
console.log(myNumArr)

其他回答

Edit

根据@Thomas的评论,在更新的TS编译器中,我们可以简单地做:

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

原来的答案

完整的例子解释了Robin引用的语法…带回家给我:

通用函数

像下面这样的东西是可以的:

function foo<T>(x: T): T { return x; }

然而,使用箭头泛型函数将不会:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

解决方法:在泛型参数上使用扩展来提示编译器 它是通用的,例如:

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

这里我有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

希望这对你有所帮助!

非箭头函数的方法。扩展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;
}

操场上

语言规范在p.64f上写着

形式为< T >(…)=>{…}可以解析为an 带有类型参数或类型断言的箭头函数表达式 应用于没有类型参数的箭头函数。它被解析为 前[. .]

例子:

// helper function needed because Backbone-couchdb's sync does not return a jqxhr
let fetched = <
           R extends Backbone.Collection<any> >(c:R) => {
               return new Promise(function (fulfill, reject) {
                   c.fetch({reset: true, success: fulfill, error: reject})
               });
           };

2021年,Ts 4.3.3

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