在Typescript中,使用字符串类型的键调用对象中的方法

在Typescript中,使用字符串类型的键调用对象中的方法,typescript,Typescript,我想用字符串类型的键调用对象中的方法,但它不起作用 我能找到解决这个问题的方法吗 type Methods = { foo?: (v: string) => string; bar?: (v: number) => number; baz?: (v: boolean) => boolean; hello?: (v: number) => string; }; function execute< I extends Met

我想用字符串类型的键调用对象中的方法,但它不起作用

我能找到解决这个问题的方法吗

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
类型方法={
foo?:(v:string)=>字符串;
条?:(v:编号)=>编号;
baz?:(v:布尔)=>布尔;
您好?:(v:number)=>字符串;
};
函数执行<
我扩展了方法,
我的K,
V扩展参数[0],
R扩展返回类型
>(方法:I,键:K,值:V):R{
返回方法[键](值);
}
常量方法:方法={
foo(v){return`${v}blah`;},
条(v){返回v+1;},
baz(v){return!v;},
hello(v){返回字符串(v);},
};
const foo=execute(方法'foo','hello');//返回字符串
const bar=execute(方法'bar',123);//返回号码
const baz=execute(方法'baz',true);//返回布尔值
const mem=execute(方法'hello',123);//返回字符串

这就是你想要做的吗?
这就是你想要做的吗?

谢谢,但实际上我想澄清
方法类型的结构。@grace请详细说明,我很困惑。你给我的方式就是我想要的方式!非常感谢。谢谢,但实际上我想澄清
方法
类型的结构。@grace请解释一下,我很困惑。你给我的方式就是我想要的方式!非常感谢。