Generic Interfaces - OOP Perspective
This lesson introduces generic types and discusses them from the perspective of Object-Oriented Programming.
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): void;
}
class ServerLoggingService implements LoggingService {
log(message: string): void {
// send logs to the server
}
}
class FooComponent {
constructor(private loggingService: ServerLoggingService) {}
}
const foo = new FooComponent(new ServerLoggingService());
Get hands-on with 1200+ tech skills courses.