add a static method to a subclass in typescript

To add a static method to a subclass in TypeScript, you can use the static keyword with the method declaration. Here's an example:

index.ts
class Animal {
  static getType(): string {
    return 'Animal';
  }
}

class Dog extends Animal {
  static getType(): string {
    return 'Dog';
  }
}

console.log(Animal.getType()); // Output: Animal
console.log(Dog.getType()); // Output: Dog
245 chars
15 lines

In the example code above, we have a parent class Animal that declares a static method getType(). This method returns the string "Animal". The Dog class extends Animal and overrides the getType() method to return "Dog".

We can then call both getType() methods using the class name and the static property accessor . notation.

Note that static methods cannot be called using an instance of the class, only using the class itself.

gistlibby LogSnag