override a static property on a subclass in typescript

To override a static property on a subclass in TypeScript, you can simply declare another static property with the same name on the subclass. This will override the corresponding static property on the parent class.

For example,

index.ts
class ParentClass {
  static staticProperty: string = 'parent';
}

class ChildClass extends ParentClass {
  static staticProperty: string = 'child';

  static printStaticProperty() {
    console.log(this.staticProperty);
  }
}

ChildClass.printStaticProperty(); // Output: "child"
281 chars
14 lines

In this example, we have two classes: ParentClass and ChildClass, with a static property staticProperty. ChildClass overrides the staticProperty with a new value of "child", and declares a static method that prints out the value of staticProperty.

When we invoke printStaticProperty() on ChildClass, it prints out the value "child", showing that the static property has been successfully overridden.

Note that unlike instance properties, static properties are shared across all instances of the class, so overriding a static property affects all instances of the subclass as well.

gistlibby LogSnag