Abstract Classes in Typescript

An abstract class is a class that cannot be instantiated. In other words, it is a class
that is designed to be derived from. The purpose of abstract classes is generally to
provide a set of basic properties or functions that are shared across a group of similar
classes. Abstract classes are marked with the abstract keyword.

Let’s take a look at the use of an abstract class, as follows:

abstract class EmployeeBase {
public id: number;
public name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
class OfficeWorker extends EmployeeBase {
}
class OfficeManager extends OfficeWorker {
public employees: OfficeWorker[] = [];
}

Here, we have defined an abstract class named EmployeeBase that has an id property
of type number, and a name property of type string. The EmployeeBase class has a
constructor function that initializes these properties. We have then defined a class
named OfficeWorker that derives from the abstract EmployeeBase class. Finally, we
have a class named OfficeManager that derives from the OfficeWorker class, and has
an internal property named employees that is an array of type OfficeWorker.

We can construct instances of these classes as follows:

let officeworker1 = new OfficeWorker(1, "ram");
let officeworker2 = new OfficeWorker(2, "shyam")
let Manager = new OfficeManager(3, "ishwori");

Here, we have created two variables named officeworker1 and officeworker2 that are of type
OfficeWorker. We have also created a variable name Manager that is of type
OfficeWorker. Note how we need to provide two arguments when constructing
these objects. This is because both the OfficeWorker class and the OfficeManager
class inherit from the abstract base class, EmployeeBase. The abstract base class
EmployeeBase requires both an id and a name argument in its constructor.

Leave a Reply

Your email address will not be published.