具有相同名称和不同参数的静态方法不起作用

时间:2020-07-06 16:57:53

标签: typescript

/********************* Parent.ts *********************/
class Parent {
    static connect(state?: string) {
        if (state) {
            // compile error
            logBar(state); // need to call logBar() in class Son.
                           // I can't call Son.logBar() since it is in Son.ts
        } else {
            // compile error
            logBar(); // need to call logBar in this class.
        }
    }

    static logBar() {
        console.log("2");
    }
}

/********************* Son.ts *********************/
// compile error :
// Class static side 'typeof Son' incorrectly extends base class
// static side 'typeof Parent'. Types of property 'logBar' are incompatible.
// Type '(state: string) => void' is not assignable to type '() => void'.
class Son extends Parent {
    static logBar(state: string) {
        console.log("1");
    }

}

/********************* test.ts *********************/

Parent.connect();
Parent.connect("hi");

调用Parent.connect();时,它应该打印出“ 2”。

调用Parent.connect("hi");时,它应该打印出“ 1”。

不可能实现抽象静态。而且它们放置在不同的文件中,因此我无法像Parent.logBar()或Son.logBar(state)那样调用。 我该怎么做?

1 个答案:

答案 0 :(得分:1)

我对类和静态函数的工作方式感到困惑。即:

  • 您不能拥有在子类上调用方法 defined 的超类。本质上,Parent不能依赖现有的Son
  • 您不能重载超类的方法。因此,即使Parent可以依赖Son,也不能更改logBar的定义。
  • 正在定义的子类不会影响通过引用超类而完成的操作。您放入Son的任何内容都不会影响Parent.logBar(...)的行为。

如果必须使用类和静态变量,那么唯一的选择就是将所有内容组合到Parent中。看起来像这样:


class Parent {
  static connect(state?: string): void {
    if (state) {
          Parent.logWithState(state);
      } else {
          // compile error
          Parent.logNoState();
      }
  }

  static logWithState(state: string): void {
    console.log("1");
  }
  static logNoState(): void 
  {
    console.log("2");
  }
}

如果您想使用继承并可以放弃静态操作,则可以执行以下操作:


class Parent {
  connect(state?: string): void {
    if (state) {
          this.logWithState(state);
      } else {
          // compile error
          this.logNoState();
      }
  }

  logWithState(state: string): void { }
  logNoState(): void { }
}

class Son extends Parent{
  logWithState(state: string) {
    console.log("1");
  }
  logNoState() {
    console.log("2");
  }
}

let ref: Parent = new Son();
ref.connect();
ref.connect("hi");

如果需要在运行时更改不同方法的行为,第二种方法将允许您细分Parent的不同子类。