首页 > 解决方案 > 如何在javascript中扩展父类的实例变量

问题描述

我正在尝试扩展父类的实例变量,但流 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)

标签: javascriptecmascript-6flowtype

解决方案


看起来 Flow 不支持覆盖类型,并且抱怨父级和子级中“广告”字段的类型冲突。不允许您更改在子级中的父级中定义的字段的类型。

这样才能维持子父关系。如果您更改子类中某个字段的类型,则当您在子类上调用它们时,您在父类中定义的函数可能不再起作用。

例如

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

你必须重组你的对象,这样就不会发生这种情况。通过将广告分解为多个字段或不使用扩展。


推荐阅读