How to use a basic way to extend the abstract class with Generics In Typescript

In this approach, we will see the basic way to extend the abstract class with generics with 3 steps:

  • Create a class with an abstract keyword and add a generic type parameter using angle brackets (<>).
  • Use the generic type parameters in methods or properties within the abstract class.
  • Extend the abstract class from other classes by providing types for the generic parameters.

Syntax:

abstract class Classname<Generic> {
Visibility Prop_Name: Generic = Initial_Value;
Method_Name(Parameter: Generic): Return_Type{ ... }
}
class NormalClass extends Abstract_Class<Generic_Type> { ... }

Example : The below example will create a simple abstract class SuperClass with a generic type parameter T. It has a method pushItem that accepts an item of type T and stores it in an array of type T[].

Javascript




abstract class SuperClass<T> {
    protected NumArray: T[] = [];
 
    pushNumber(num: T): void {
        this.NumArray.push(num);
    }
 
    abstract ShowNumbers(): void;
}
 
class SubClass extends SuperClass<number> {
    showNumbers(): void {
        console.log("Pushed Numbers are: ",
        this.NumArray.join(", "));
    }
}
 
const numberSeries = new SubClass();
numberSeries.pushNumber(1);
numberSeries.pushNumber(2);
numberSeries.showNumbers();


Output:

Pushed Numbers are: 1, 2

How to Extend abstract class with Generics in Typescript ?

In Typescript, an abstract class is the base class that is inherited by other classes without having to define its members. Generic is the feature with which you can create a variable that represents a type in classes, functions, and type aliases that don’t need to define the types that they use explicitly.

There are 3 approaches given below to extend an abstract class with generics:

Table of Content

  • Using a basic way to extend the abstract class with Generics
  • Extending with Generic Constraints
  • With multiple type parameters in Generics

Similar Reads

Using a basic way to extend the abstract class with Generics

In this approach, we will see the basic way to extend the abstract class with generics with 3 steps:...

Extending with Generic Constraints

...

With multiple type parameters in Generics

Extending with the use of Generic Constraints can be done in the following 4 steps:...