简体   繁体   English

在打字稿中扩充抽象方法

[英]Augment abstract method in typescript

I have abstract class Command with abstract method " execute() ".我有抽象类Command和抽象方法“ execute() ”。 A lot of other commands extend it.许多其他命令扩展了它。 Each has its own " execute() " implementation.每个都有自己的“ execute() ”实现。

How can I add some common logic (like logging) each time when any command gets executed?每次执行任何命令时,如何添加一些通用逻辑(如日志记录)?

export abstract class Command {
    public abstract execute(...commandParams: any[]): void;
}

In my opinion the best way to handle this is at the point where you call the execute method rather than inside the method itself.在我看来,处理这个问题的最好方法是在调用execute 方法时而不是在方法本身内部。

You're not going to get good typechecking on your execute function arguments since they are defined as ...commandParams: any[] .您不会对execute函数参数进行良好的类型检查,因为它们被定义为...commandParams: any[] This is a place where we can make use of generics to enforce that all Command types fit a general interface while also not losing information about their unique arguments.在这里,我们可以使用泛型来强制所有Command类型适合通用接口,同时不会丢失有关其唯一参数的信息。

FYI, This could just as well be an interface instead of an abstract class .仅供参考,这也可以是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);
    }
}

Playground Link 游乐场链接

The generic T in the Executer says that we can pass in any type of Command , but that the arguments have to match the expected arguments for that specific command type. Executer的泛型T表示我们可以传入任何类型的Command ,但参数必须与该特定命令类型的预期参数匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM