typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
当前回答
我喜欢使用这种类型的声明:
const identity: { <T>(arg: T): T } = (arg) => arg;
它允许在需要时为函数定义额外的道具,在某些情况下,它有助于使函数体相对于泛型定义更清晰。
如果你不需要额外的道具(命名空间之类的东西),它可以简化为:
const identity: <T>(arg: T) => T = (arg) => arg;
其他回答
这对我很有用
const Generic = <T> (value: T) => {
return value;
}
语言规范在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})
});
};
这么晚了,但与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)
添加多个依赖泛型类型的示例:
这个函数,转换为箭头函数,如下所示:
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,>,因为它解决了这个问题。我还不知道原因。但这对我很管用。