I am looking for a way to call methods in an Object using string keys, but I'm facing issues with it.
Could someone provide some solutions for this?
type Methods = {
foo?: (v: string) => string;
bar?: (v: number) => number;
baz?: (v: boolean) => boolean;
hello?: (v: number) => string;
};
function execute<
I extends Methods,
K extends keyof I,
V extends Parameters<I[K]>[0],
R extends ReturnType<I[K]>
>(methods: I, key: K, value: V): R {
return methods[key](value);
}
const methods: Methods = {
foo(v) { return `${v}blah`; },
bar(v) { return v + 1; },
baz(v) { return !v; },
hello(v) { return String(v); },
};
const foo = execute(methods, 'foo', 'hello'); // returns string
const bar = execute(methods, 'bar', 123); // returns number
const baz = execute(methods, 'baz', true); // returns boolean
const mem = execute(methods, 'hello', 123); // returns string