dorachan2010
dorachan2010

Reputation: 1091

How to extend a parent class' instance variable in javascript

I am trying to extend a parent class's instance variable but flow js is complaining that this is not correct. Is there something I am missing?

// 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)

Upvotes: 2

Views: 922

Answers (1)

Shimmy568
Shimmy568

Reputation: 503

It doesn't look like Flow supports overriding types and is complaining about the type conflict for the "ads" field in the parent and the child. You aren't allowed to change the type of a field that's been defined in the parent in the child.

This is so the child parent relationship is maintained. If you change the type of one of the fields on a child class the functions that you defined in the parent may no longer function when you call them on the child.

e.g.

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

You'll have to restructure you objects so this doesn't happen. Either by breaking down ads into multiple fields or by not using extends.

Upvotes: 1

Related Questions