First, create an interface for the dependency you want to inject, for example:
interface Logger {
log(message: string): void;
}
Next, create a class that implements the interface:
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}
Now, create a class that depends on the Logger interface:
class MyClass {
private logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
doSomething(): void {
this.logger.log('Doing something...');
}
}
Finally, create an instance of the Logger implementation and pass it to the constructor of the class that depends on it:
const logger = new ConsoleLogger();
const myClass = new MyClass(logger);
myClass.doSomething();
This example demonstrates how Dependency Injection can be implemented in TypeScript using classes. By using interfaces to define dependencies, you can easily swap out implementations without changing the code that depends on them.