[英]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.