Inheritance in TypeScript
Inheritance is a key aspect of object-oriented programming that allows a class to inherit properties and methods from another class, promoting code reuse and hierarchy. Through the use of the extends keyword, a derived class can inherit the members of a base class and can further extend or override them. This mechanism supports the creation of a hierarchical structure where a subclass inherits the behavior of its superclass, allowing for the development of more specialized classes while maintaining a shared set of characteristics.
TypeScript enforces type safety in inheritance, providing a statically typed way to express relationships between classes and ensuring that derived classes conform to the interface defined by their base classes. The combination of inheritance with other OOP features such as encapsulation and polymorphism contributes to the creation of scalable and maintainable software systems.
Basic Inheritance
This example shows how Employee inherits all properties and methods from Person using the extends keyword. It adds its own salary property and introduce method, building upon the functionality of the parent class.
Constructor Chaining
Here, Manager extends Employee and chains the parent constructor call to initialize inherited properties. It adds a department property and a leadMeeting method showcasing further specialization.
Super Keyword
This example demonstrates the super keyword. Doctor uses it to access the parent's greet method within its own method, extending its functionality with additional information.
Access Modifiers and Inheritance
This example showcases access modifiers. While mission is private in SecretAgent, a public method can access it to generate a codename, demonstrating controlled inheritance without revealing sensitive information.
Abstract Classes
TypeScript supports abstract classes, which are classes that cannot be instantiated directly and are meant to serve as base classes for other classes.
The Shape class is abstract and enforces that any class extending it must provide its own implementation of the abstract method calculateArea.
Conclusion
TypeScript inheritance allows classes to inherit properties and methods from a base class, facilitating code reuse and creating class hierarchies. It supports method overriding, access modifiers, and abstract classes to enhance code organization and structure.