Generic Interfaces - OOP Perspective
Explore how generic interfaces in TypeScript align with object-oriented programming concepts, enabling flexible dependencies and rigorous type safety. Understand examples like the Observer interface and ReadonlyArray to grasp generic methods and compile-time guarantees.
We'll cover the following...
Interfaces in Object-Oriented Programming
Interfaces in TypeScript are very flexible and have multiple uses. One way of looking at them is from the perspective of Object-Oriented Programming (OOP). In this context, an interface defines a list of methods that a class needs to implement in order to conform to the interface.
OOP interfaces are often used to fulfill the Dependency Inversion Principle from SOLID design principles. A class (e.g., an Angular component) might have dependencies (e.g., an Angular service). Dependencies are things that you need to provide to the constructor of the class to create an instance of it. The principle says that it’s much better to have interfaces than concrete classes as dependencies.
If the class requires a concrete class (e.g., a ServerLoggingService class), it’s difficult to replace the dependency. For example, unit testing such a class is much harder since you have to provide an instance of this concrete class.
interface LoggingService {
log(message: string): ...