[英]Augment abstract method in typescript
我有抽象类Command
和抽象方法“ execute()
”。 许多其他命令扩展了它。 每个都有自己的“ execute()
”实现。
每次执行任何命令时,如何添加一些通用逻辑(如日志记录)?
export abstract class Command {
public abstract execute(...commandParams: any[]): void;
}
在我看来,处理这个问题的最好方法是在调用execute 方法时而不是在方法本身内部。
您不会对execute
函数参数进行良好的类型检查,因为它们被定义为...commandParams: any[]
。 在这里,我们可以使用泛型来强制所有Command
类型适合通用接口,同时不会丢失有关其唯一参数的信息。
仅供参考,这也可以是interface
而不是abstract class
。
interface Command<T extends any[]> {
execute( ...commandParams: T): void;
toString(): string;
}
class Executer {
execute<T extends any[]>( command: Command<T>, ...args: T ) {
command.execute(...args);
}
executeAndLog<T extends any[]>( command: Command<T>, ...args: T ) {
console.log( `executing command ${command.toString()} with arguments:`, ...args );
command.execute(...args);
}
}
Executer
的泛型T
表示我们可以传入任何类型的Command
,但参数必须与该特定命令类型的预期参数匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.