Extending with Generic Constraints
Extending with the use of Generic Constraints can be done in the following 4 steps:
- Create an interface of generic type with constraints
- Create an abstract class with a generic type parameter constrained by the above interface
- Extend the abstract class with a class that implements the interface
- Extend the abstract class with the normal class by which the normal class will have the power to pass a class as a type
Syntax:
interface Interface_Name{ ... }
abstract class AbstractClass<T extends Interface_Name> { ... }
class ClassNameOne implements Interface_Name{ ... }
class ClassNameTwo extends AbstractClass<ClassNameOne > { ... }
Example: The below example creates a class that extends an abstract class with passing another class as a generic and the generic also extends some interface.
Javascript
interface MethodGateway { printName(): string; } abstract class AbstractClass<T extends MethodGateway> { abstract printName(): T; } class ClassMethodExtender implements MethodGateway { printName(): string { return "w3wiki" ; } } class NormalClass extends AbstractClass<ClassMethodExtender> { printName(): ClassMethodExtender { return new ClassMethodExtender(); } } const instance = new NormalClass(); console.log(instance.printName().printName()); |
Output:
w3wiki
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