I am looking to create a function that serves as a shortcut for obj.func.bind(obj)
. It should work like this:
const bound = <...>(obj: ..., fnKey: ...) : ... => obj[fnKey].bind(obj);
const obj = {
a: "abc",
b() {
console.log(this.a);
}
}
const f = bound(obj, "b"); //it would be great if intellisense displayed all keys with a function value as the second argument
f(); //typed correctly
I have tried various options, one of them being:
function bound<
K extends string,
F extends (...args: any[]) => any,
T extends {[key in K]: F}
>(thisObj: T, fnKey: K): (...args: Parameters<F>) => ReturnType<F> {
const fn : F = thisObj[fnKey];
return fn.bind(thisObj);
}
However, none of them seem to yield the expected result, as the return value is typed incorrectly:
const obj = {
a: "abc",
foo() {
console.log(this.a);
},
};
const f = bound(obj, "foo"); //(...args: any[]) => any
Additionally, when I try to avoid 'any' and specify
F extends (...args: never[]) => unknown
, I receive a TypeScript error Type 'unknown' is not assignable to type 'ReturnType<F>'
.
The @types/lodash definition seems to have left this function essentially untyped.