override a private property on a subclass in typescript

To override a private property on a subclass in TypeScript, you can declare a public property with the same name as the private property on the base class. You can then use the super keyword to access the private property from the base class and assign it to the public property on the subclass.

index.ts
class Base {
  private foo: string = "base";

  constructor() {}

  public getFoo(): string {
    return this.foo;
  }
}

class Subclass extends Base {
  public foo: string = "subclass";

  constructor() {
    super();
    console.log(super.getFoo()); // logs "base"
  }
}

const s = new Subclass();
console.log(s.foo); // logs "subclass"
339 chars
22 lines

In this example, we have a Base class with a private property foo that is set to "base". We then declare a Subclass that extends the Base class and overrides the foo property with a public property that is set to "subclass". In the Subclass constructor, we call the super constructor to instantiate the Base class and then use super.getFoo() to access the private foo property on the Base class and log it to the console. Finally, we create an instance of Subclass and log the foo property, which logs "subclass" because it is overridden in the Subclass.

gistlibby LogSnag