/********************* 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)那样调用。 我该怎么做?
答案 0 :(得分:1)
我对类和静态函数的工作方式感到困惑。即:
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
的不同子类。