typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
typescript手册目前没有关于箭头函数的内容。正常的功能 可以使用以下语法进行泛型: 例子:
function identity<T>(arg: T): T {
return arg;
}
箭头函数的语法是什么?
当前回答
添加多个依赖泛型类型的示例:
这个函数,转换为箭头函数,如下所示:
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 identity: { <T>(arg: T): T } = (arg) => arg;
它允许在需要时为函数定义额外的道具,在某些情况下,它有助于使函数体相对于泛型定义更清晰。
如果你不需要额外的道具(命名空间之类的东西),它可以简化为:
const identity: <T>(arg: T) => T = (arg) => arg;
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;
非箭头函数的方法。扩展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;
}
操场上
这对我很有用
const logSomething = <T>(something:T): T => {
return something;
}
使用<T, extends{}>在试图传递null作为参数时抛出错误。我更喜欢使用<T,>,因为它解决了这个问题。我还不知道原因。但这对我很管用。