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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With