我正在尝试扩展父类的实例变量,但js流程抱怨这是不正确的。有什么我想念的吗?
// BaseClass
export type AdType = {
dom: HTMLElement,
};
export default class AdsRefresh {
ads: AdType[] = [];
constructor(configs) {
this.ads = configs;
}
}
// ChildClass
import type {AdType as BaseAdType, PlaceholderType} from './adsRefresh';
export type AdType = {
placeholderIndex?: number
} & BaseAdType;
class AdsRefreshTiler extends AdsRefresh {
ads: AdType[] = [];
constructor(configs) {
super(configs);
this.ads = this.getAds(configs);
}
}
Cannot extend `AdsRefresh` [1] with `AdsRefreshTiler` because property `placeholderIndex` is missing in `AdType` [2] but exists in object type [3] in property `ads`.Flow(InferError)
看起来Flow不支持覆盖类型,并且抱怨父级和子级中“ ads”字段的类型冲突。您不允许更改在子代的父代中定义的字段类型。
这样可以保持孩子的父母关系。如果更改子类中字段之一的类型,则在子类上调用它们时,在父类中定义的功能可能不再起作用。
例如
export default class Parent {
felid1: number;
parentFunction() {
return this.felid1 / 3;
}
}
class Child extends Parent {
field1: string; // Now the parentFunction wont work since you can't divide strings
}
var a = new Parent();
a.felid1 = 1;
a.parentFunction(); // Does not crash
var c = new Child();
c.field1 = "a";
c.parentFunction(); // Crashes
您必须重组对象,以免发生这种情况。通过将广告细分为多个字段,或不使用扩展。