typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
当前回答
这对我很有用
const Generic = <T> (value: T) => {
return 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
希望这对你有所帮助!
添加多个依赖泛型类型的示例:
这个函数,转换为箭头函数,如下所示:
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;
...
};
这对我很有用
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 Generic = <T> (value: T) => {
return value;
}