0
这是我的示例代码。 [TS]元素含蓄有一个“任意”类型,因为类型“计算机”没有指数的签名元素隐含有'任何'类型,因为类型'计算机'没有索引签名
interface iAdd {
add(a: number): number;
}
class Computer implements iAdd {
add(a: number): number {
return a + 1;
}
add10(a: number): number {
return a + 10;
}
}
var computer = new Computer();
console.log(computer.add(1));
console.log(computer.add10(1));
// for now everything is working, however what i want is below,
let methodName:string = 'add10';
computer[methodName]();
// now there is an error:
// I don't want to use this way to fix, i want a safer way.
(<any>computer)[methodName](); // don't want this fix
请帮我
感谢Nitzan为您解答。我真正的问题是,我不知道它会有多少功能,计算机类也可以继承。它会引入更多的功能,我希望methodName可以是动态的,真正的功能将在实时确定。我怎样才能做到这一点? –
应该使用我给出的最后一个选项(使用'keyof')。如果您遇到问题,请使用示例更新问题。 –