override a property on a subclass in typescript

To override a property on a subclass in TypeScript, you can simply declare a property with the same name in your subclass and assign it a new value. Here's an example:

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

class Dog extends Animal {
  move(distance: number = 0) {
    console.log(`Dog moved ${distance}m.`);
    super.move(distance);
  }
}

const animal = new Animal();
const dog = new Dog();
animal.move(); // output: "Animal moved 0m."
dog.move(10); // output: "Dog moved 10m." followed by "Animal moved 10m."
406 chars
18 lines

In this example, we have defined a base class Animal with a method move that logs a message to the console. We then create a subclass Dog that extends Animal and overrides the move method to first log a message specific to dogs and then call the base move method using super.move(distance).

Testing the output of both the Animal and Dog instances shows that the move method of Dog overrides the move method of Animal and logs a different message.

gistlibby LogSnag