Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a generic function using function.call()?

usually generic functions are defined and called like so:

function identity<T>(arg: T): T {
    return arg;
}
const id1 = identity<string>("hei");

Is there a way to call generic functions with function.bind(), function.call(), or function.apply()? How do I specify the type arguments?

This, for example, is compiled correctly, but the compiler gives me an error.

function boundIdentity<T>(this: T): T {
    return this;
}
const id2 = boundIdentity.call<Object>({});

If I remove the type argument, the function works as expected, but I don't get type inference on id2.

See in Typescript Playground

like image 555
Marcoq Avatar asked Mar 02 '17 15:03

Marcoq


1 Answers

Yes.

You can create an interface that describes what you want like this:

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

And use it like this:

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

And now you will get type inference when you do this:

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

See in TypeScript Playground

like image 120
Seamus Avatar answered Oct 05 '22 04:10

Seamus