add a setter to a subclass in typescript

To add a setter to a subclass in TypeScript, we can define a setter in the subclass and use the super keyword to access and set the value of the property in the parent class. Here's an example:

index.ts
class Person {
  private _name: string;

  constructor(name: string) {
    this._name = name;
  }

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

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

class Employee extends Person {
  private _salary: number;

  constructor(name: string, salary: number) {
    super(name);
    this._salary = salary;
  }

  get salary(): number {
    return this._salary;
  }

  set salary(salary: number) {
    this._salary = salary;
  }
}
481 chars
33 lines

In this example, the Employee class extends the Person class and defines a salary property with a getter and a setter. The super keyword is used in the constructor of the Employee class to call the constructor of the parent class and pass the name argument to it.

To set the value of the name property in the Person class from the Employee class, we can use the super keyword in the set method of the name property, like this:

index.ts
class Employee extends Person {
  // ...

  set name(name: string) {
    super.name = name;
    // additional logic specific to Employee class...
  }
}
152 chars
9 lines

In this example, the set method of the name property in the Employee class assigns the new value of name to the name property in the Person class using super.name = name;. This allows us to reuse the name property implementation from the parent class and add additional logic specific to the Employee class.

gistlibby LogSnag