2017-03-02 56 views
2

通常泛型函数的定义,并呼吁像这样:我可以使用function.call()调用通用函数吗?

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拿到类型推断。

See in Typescript Playground

回答

1

是的。

您可以创建一个接口,描述你想要的东西是这样的:当你做这个

let boundIdentity: IBoundIdentityFunction = function<T>(this: T): T { 
    return this; 
} 

而现在你会得到类型推断:

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

而且使用这样的

const id2 = boundIdentity.call<Object>({}); 

See in TypeScript Playground

相关问题