override a private static property on a subclass in typescript

To override a private static property on a subclass in TypeScript, you can use Object.defineProperty() method to define a new value for the private static property.

Here's an example:

index.ts
class ParentClass {
  private static myPrivateStaticProperty = 'parentValue';

  static getMyPrivateStaticProperty() {
    return this.myPrivateStaticProperty;
  }
}

class ChildClass extends ParentClass {
  static overrideMyPrivateStaticProperty() {
    Object.defineProperty(this, 'myPrivateStaticProperty', {
      value: 'childValue',
      writable: false,
    });
  }
}

console.log(ParentClass.getMyPrivateStaticProperty()); // output: parentValue
ChildClass.overrideMyPrivateStaticProperty();
console.log(ParentClass.getMyPrivateStaticProperty()); // output: childValue
578 chars
21 lines

In the ChildClass, we use Object.defineProperty() to set a new value for the myPrivateStaticProperty.

Note that since myPrivateStaticProperty is private, we cannot access it directly outside the class, but we can define a static method getMyPrivateStaticProperty() to get its value.

gistlibby LogSnag