我可以使用function.call()调用泛型函数吗?

Mar*_*coq 5 generics call typescript

通常,通用函数的定义和调用方式如下:

function identity<T>(arg: T): T {
    return arg;
}
const id1 = identity<string>("hei");
Run Code Online (Sandbox Code Playgroud)

有没有一种方法来调用通用功能与function.bind()function.call()function.apply()?如何指定类型参数?

例如,这已正确编译,但是编译器给我一个错误。

function boundIdentity<T>(this: T): T {
    return this;
}
const id2 = boundIdentity.call<Object>({});
Run Code Online (Sandbox Code Playgroud)

如果我删除类型实参,则该函数将按预期工作,但不会在上得到类型推断id2

在打字稿游乐场中查看

Sea*_*mus 5

是的。

您可以创建一个描述您想要的界面的界面,如下所示:

interface IBoundIdentityFunction {
    <T>(this: T): T;
    call<T>(this: Function, ...argArray: any[]): T;
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

let boundIdentity: IBoundIdentityFunction = function<T>(this: T): T {
    return this;
}
Run Code Online (Sandbox Code Playgroud)

现在,当您执行此操作时,您将获得类型推断:

const id2 = boundIdentity.call<Object>({});
Run Code Online (Sandbox Code Playgroud)

在 TypeScript Playground 中查看