使用抽象方法实例化类

Ale*_*lls 0

使用Java,我们可以创建一个ActionListener类的实例,它有一个抽象方法,就像这样(它已经有一段时间了):

new ActionListener(){
  @Override
  public void actionPerformed(ActionEvent e) {
     // whatever
  }
}
Run Code Online (Sandbox Code Playgroud)

使用TypeScript,这是我能得到的最接近的:

export abstract class ActionListener {

  constructor(f: any) {
    this.actionPerformed = f;
  }

  abstract actionPerformed(input: string): string;

}


new ActionListener(input => {

});
Run Code Online (Sandbox Code Playgroud)

至少有两个问题:

  1. 如果你使用带有TS的抽象方法,那么类必须抽象(我认为使用Java你可以使用抽象方法,以后可以实现).

  2. 我不知道如何将输入函数f的类型绑定/绑定到解析方法的类型.

有谁知道有没有办法用TS做到这一点?

也许我们不能使用abstractTS,并且必须更像这样:

type ActionPerformed = (input: string) => string;

export class ActionListener {

  parse: ActionPerformed;

  constructor(f: ActionPerformed) {
    this.parse = f;
  }

}

new ActionListener(input => {
  return 'foo';
});
Run Code Online (Sandbox Code Playgroud)

Jör*_*tag 5

使用Java,我们可以创建一个ActionListener类的实例,该实例具有抽象方法

不,您不能创建具有抽象方法的类的实例.当你调用那个抽象方法时会发生什么?

可以做的是您可以创建实现该抽象方法的抽象类的类,并且您可以创建该子类的实例.这正是您的Java代码正在做的事情.您的Java代码没有实例化对象ActionListener.您的Java代码正在创建一个子类,ActionListener子类将覆盖actionPerformed并实例化该子类.

现在,当然,TypeScript支持子类化,因此您可以在TypeScript中执行完全相同的操作:创建子类,覆盖/实现该方法,然后实例化该子类:

new (class extends ActionListener { 
    actionPerformed(input: string): string {
        return "Hello"
    }
})(input => {
    // Whatever
});
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做:

new (class implements ActionListener {
  actionPerformed(input: string): string {
    return "Hello"
  }
});
Run Code Online (Sandbox Code Playgroud)

这里的游乐场.