typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
当前回答
2021年,Ts 4.3.3
const useRequest = <DataType, ErrorType>(url: string): Response<DataType, ErrorType>
=> {
...
}
其他回答
语言规范在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})
});
};
我知道我回答这个问题有点晚了。但我想到了回答这个问题,以防其他人发现它有帮助。没有一个答案提到如何在异步箭头函数中使用泛型。
是这样的:
const example = async <T> (value: T) => {
//awaiting for some Promise to resolve or reject;
const result = await randomApi.getData(value);
}
这里我有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
希望这对你有所帮助!
这对我很有用
const Generic = <T> (value: T) => {
return value;
}
2021年,Ts 4.3.3
const useRequest = <DataType, ErrorType>(url: string): Response<DataType, ErrorType>
=> {
...
}