TypeScript如何运行时为类方法添加函数体并解决相关类型报错?
问题解决方案
问题1:参数传递错误解决
你之前把入参_args定义在了functionBody的参数列表里,实际应该由functionBody返回的异步函数接收任意入参,再透传给目标方法。调整后functionBody只需要接收方法名这一个入参,返回的函数用剩余参数接收所有调用时传入的参数即可。
问题2:类型索引错误解决
报错的核心是functionName为any类型,无法合法索引IBaseCommandingController接口。规范解法是约束functionName的类型为keyof IBaseCommandingController,配合类型断言即可通过类型校验。
完整可运行代码示例
export class MyClass { private commandingController?: IBaseCommandingController; constructor(args: any) { // 其他构造逻辑 this.wrapBody(); } private async getCommandingController() { // 补全之前漏写的this关键字 if (this.commandingController !== undefined) return this.commandingController; this.commandingController = await someAsyncCall(); return this.commandingController; } private wrapBody() { // 过滤需要包装的方法,同时做类型断言限定方法名范围 const methods = Object.getOwnPropertyNames(this).filter( (item) => typeof this[item as keyof MyClass] === 'function' && item !== 'wrapBody' && item !== 'getCommandingController' // 可选优化:如果业务方法都有统一前缀可以加这行过滤,避免误包装其他方法 // && item.startsWith('on') ) as Array<keyof IBaseCommandingController>; methods.forEach((functionName) => { this[functionName as keyof MyClass] = this.functionBody(functionName) as any; }); } // 仅接收方法名参数,返回的异步函数用剩余参数透传所有入参 private functionBody = (functionName: keyof IBaseCommandingController) => { return async (...args: any[]) => { // 修正笔误,调用你定义的getCommandingController方法 const commanding = await this.getCommandingController(); commanding[functionName](...args); }; }; // 业务方法仅需要定义类型,不需要写内部逻辑 private onInsert = async (_arg: InsertArguement) => {}; private onDelete = async (_arg: DeleteArguement) => {}; private onUpdate = async (_arg: UpdateAruement) => {}; // 其他同类业务方法 }
内容的提问来源于stack exchange,提问作者Devendra Verma
相关产品推荐
相关产品推荐

