我能使用function.call()调用一个泛型函数吗?

8
通常情况下,泛型函数的定义和调用方式如下所示:
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>({});

如果我删除类型参数,该函数将按预期工作,但我不会在id2上获得类型推断。 在Typescript Playground中查看
2个回答

6

可以的。

您可以创建一个描述您想要的接口,就像这样:

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>({});

See in TypeScript Playground


1
现在可以使用实例化表达式来完成这个任务。
const boundIdentityWithType = boundIdentity<Object>;
const id2 = boundIdentity.call({});

Typescript Playground


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接