The abstract Method in TypeScript

Rana Hasnain Khan Feb 02, 2024
The abstract Method in TypeScript

We will introduce what an abstract method is in TypeScript with examples. We will also present an abstract class in TypeScript with examples.

Abstract Method in TypeScript

When working on commercial applications, we need to define some common behavior or functionality that can later be used for multiple purposes; for this purpose, TypeScript comes with a feature known as abstract. We can define classes using this keyword and common behaviors using abstract methods inside abstract classes.

The word abstract is mainly used for classes in TypeScript. When we want to define a common behavior in a class from which more classes can be derived, it is known as an abstract class.

The keyword abstract is used to define an abstract class.

Every abstract class consists of one or more abstract methods defined with the keyword abstract. Abstract methods are the methods that transfer the common functionality to the derived classes.

The derived classes must define all the abstract methods defined in the main class.

Let’s go through an example where we will create an abstract class with an abstract method, as shown below.

# TypeScript
abstract class Course {
    courseName: string;

    constructor(courseName: string) {
        this.courseName = Typescript;
    }

    abstract search(string): Course;
}

As you can see from the above example, we created an abstract class Course in which we defined an abstract method search. Let’s derive another class from this class and use its methods, as shown below.

# TypeScript
abstract class Course {
    courseName: string;

    constructor(courseName: string) {
        this.courseName = courseName;
    }
    abstract search(string): Course;
}

class Subject extends Course {
    subCode: number;

    constructor(courseName: string, subCode: number) {
        super(courseName);
        this.subCode = subCode;
    }

    search(courseName:string): Course {
        return new Subject(courseName, 1);
    }
}

let sub: Course = new Subject("Typescript", 101);

let sub2: Course = sub.search('Javascript');

This way, we can use the abstract method inside the derived classes.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn