JavaScript – How to Use Interfaces in Dependency Injection

dependency-injectioninterfacesjavascript

I'm working on a simple DI library, and on the subject of using services through interfaces, I can't find the usefulness. Perhaps it's because I dont fully or properly understand how an interface should be used during the process of injecting dependencies.

Here's what I (think I) understand:

DI consists primarily of clients and services. Interfaces allow the injector to tell the client which variables and methods are available through a specific service.

If that isn't wrong:

It seems to me that the interface could pass available property names and what type they are, so my client can know if they're functions or values, but that doesn't seem useful since I can do that with or without the interface. Whether the methods/values are utilized via an interface or via the injected service, I can know their types because I can use the typeof operand (JavaScript) regardless to check the type of the property I'm about to use.

So I think that I must not have a proper understanding of what interfaces should do. How are interfaces used in dependency injection?

Best Answer

The benefit isn't that the interface declares the members and methods that a client needs--which is exactly what a concrete class can do. The benefit is that a concrete class can implement an interface, which allows you to swap out the dependency at run-time. For testing, you may want to pass in a mock implementing the same interface, but without all the overhead of the usual class (database calls, perhaps). Your class only depends on an interface, but the implementation is left for the DI/IoC container to inject.