create a subclass in typescript

To create a subclass in TypeScript, you can use the extends keyword along with the super keyword. Here's an example:

index.ts
class Person {
  protected name: string;

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

  sayName() {
    console.log(`My name is ${this.name}`);
  }
}

class Employee extends Person {
  private department: string;

  constructor(name: string, department: string) {
    super(name);
    this.department = department;
  }

  sayDepartment() {
    console.log(`I work in ${this.department}`);
  }
}

const john = new Employee('John Doe', 'Marketing');
john.sayName(); // Output: My name is John Doe
john.sayDepartment(); // Output: I work in Marketing 
562 chars
29 lines

In this example, we have a Person class with a name property and a sayName() method. Then, we have an Employee class that extends Person and adds a department property and a sayDepartment() method.

To create an instance of the Employee class, we use the new keyword and pass in a name and department argument to the constructor. We then call the sayName() and sayDepartment() methods to print out the name and department of the employee.

By using inheritance and subclasses, we can reuse code and create more specific classes that build on top of more general ones.

gistlibby LogSnag