通常定义和调用泛型函数,如下所示:
function identity<T>(arg: T): T {
return arg;
}
const id1 = identity<string>("hei");
有没有办法用function.bind(),function.call()或function.apply()调用泛型函数?如何指定类型参数?
例如,这是正确编译的,但编译器给了我一个错误.
function boundIdentity<T>(this: T): T {
return this;
}
const id2 = boundIdentity.call<Object>({});
如果我删除了type参数,该函数按预期工作,但我没有在id2上获得类型推断.
最佳答案 是.
您可以创建一个描述所需内容的界面:
interface IBoundIdentityFunction {
<T>(this: T): T;
call<T>(this: Function, ...argArray: any[]): T;
}
并像这样使用它:
let boundIdentity: IBoundIdentityFunction = function<T>(this: T): T {
return this;
}
现在,当您执行此操作时,您将获得类型推断:
const id2 = boundIdentity.call<Object>({});