override a public property on a subclass in typescript

To override a public property on a subclass in TypeScript, you can follow these steps:

  1. Extend the superclass and create a subclass.
  2. Declare the same property in the subclass with a different value or implementation.
  3. Call the superclass constructor using the "super" keyword, passing in any required arguments.
  4. Set the overridden property on the subclass to the desired value.

Here is an example code snippet demonstrating this process:

index.ts
class Animal {
  public name: string;
  constructor(name: string) {
    this.name = name;
  }
}

class Dog extends Animal {
  public breed: string;
  constructor(name: string, breed: string) {
    super(name);
    this.breed = breed;
  }

  // Override the "name" property in the subclass
  public get name(): string {
    return `Dog: ${super.name}`;
  }
}

const doggo = new Dog("Max", "Golden Retriever");
console.log(doggo.name); // Output: "Dog: Max"
console.log(doggo.breed); // Output: "Golden Retriever"
512 chars
24 lines

In this example, we have a superclass called "Animal" with a public property called "name". We create a subclass called "Dog" which extends "Animal" with an additional public property called "breed". We override the "name" property in the Dog subclass by creating a new getter function that prefixes the name with "Dog: ". When we create a new instance of Dog and call the "name" property, the overridden function is called, and the output is "Dog: Max".

gistlibby LogSnag