override a setter on a subclass in typescript

To override a setter on a subclass in TypeScript, you simply define a setter on the subclass with the same name as the parent, and then invoke super inside of it to call the parent's implementation.

Consider the following example:

index.ts
class Animal {
  private _name: string = "";

  public get name(): string {
    return this._name;
  }

  public set name(value: string) {
    this._name = value;
  }
}

class Dog extends Animal {
  public set name(value: string) {
    super.name = value.toUpperCase();
  }
}

const myDog = new Dog();
myDog.name = "Fido";
console.log(myDog.name); // "FIDO"
358 chars
22 lines

In this example, we have a base Animal class with a name property, which has a getter and setter. We then define a Dog class which extends Animal, and overrides the name setter to convert the name to uppercase.

When we create a new Dog instance and set its name to "Fido", the overridden setter is invoked, which calls super.name = value.toUpperCase(); to set the name on the parent Animal class with an uppercase string.

We then log the name property of the myDog instance, and see that it has been converted to "FIDO".

gistlibby LogSnag