override a method on a subclass in typescript

To override a method on a subclass in TypeScript, first, define the subclass that extends the base class that contains the method you want to override. Then, define the method on the subclass with the same name as the method on the base class.

To override the method, use the super keyword in the method definition of the subclass to call the original method from the base class, and then provide your custom implementation after the call to super.

Here's an example:

index.ts
class BaseClass {
  public myMethod(): void {
    console.log('This is the base class method.');
  }
}

class SubClass extends BaseClass {
  public myMethod(): void {
    super.myMethod();
    console.log('This is the sub class method that overrides the base class method.');
  }
}

const mySubClass = new SubClass();
mySubClass.myMethod(); // "This is the base class method." "This is the sub class method that overrides the base class method."
446 chars
16 lines

In this example, the SubClass extends the BaseClass and the myMethod() method is overridden. When we call myMethod() on an instance of SubClass, it calls the original method from the BaseClass using the super keyword and then provides its own custom implementation.

gistlibby LogSnag