add a getter to a subclass in typescript

In TypeScript, you can add a getter to a subclass by defining a getter in the sub class using the get keyword. The method signature of the getter should be the same as that of the property being accessed. Here's an example:

index.ts
class Person {
  constructor(private _name: string) {}
  
  get name(): string {
    return this._name;
  }
}

class Employee extends Person {
  constructor(name: string, private _salary: number) {
    super(name);
  }
  
  get salary(): number {
    return this._salary;
  }
}

const emp = new Employee("John Doe", 50000);
console.log(emp.name); // output: "John Doe"
console.log(emp.salary); // output: 50000
411 chars
22 lines

In the above example, the Person class has a getter for the name property. The Employee class extends the Person class and adds a getter for the salary property. When we create an instance of the Employee class, we can access both the name and salary properties using the getter methods.

gistlibby LogSnag