add a method to a subclass in typescript

To add a method to a subclass in TypeScript, you can extend the subclass from its parent class, and then define a new method in the subclass. Here is an example:

index.ts
class Animal {
  move(distanceInMeters: number = 0) {
    console.log(`Animal moved ${distanceInMeters}m.`);
  }
}

class Dog extends Animal {
  bark() {
    console.log('Woof! Woof!');
  }
  
  move(distanceInMeters: number = 5) {
    console.log('Running...');
    super.move(distanceInMeters);
  }
}

const dog = new Dog();

dog.bark(); // output: 'Woof! Woof!'
dog.move(); // output: 'Running... Animal moved 5m.'
418 chars
22 lines

In this example, we define an Animal class with a move method. Then, we extend the Dog subclass from the Animal class, and define a new method bark in Dog. We also override the move method in Dog, to add a custom behavior before calling the parent method using the super keyword.

Now, we can create an instance of Dog and call its methods, and it will output Woof! Woof! and Running... Animal moved 5m. respectively.

gistlibby LogSnag