5 ms·
Its true that, by default, you use a Class when wiring up the DI container because as you guessed, the interfaces are erased during transpilation. You can stil
by adamkl 6y ago
Its true that, by default, you use a Class when wiring up the DI container because as you guessed, the interfaces are erased during transpilation.
You can still achieve the loose coupling of DI by using custom providers [0]. Basically, this approach is the full syntax for defining providers and gives you the most flexibility (inject based on Class or token, provide factories, simple values, class instances, etc).
[0]: https://docs.nestjs.com/fundamentals/custom-providers#custom-providers-1 https://docs.nestjs.com/fundamentals/custom-providers#custom...
- egeozcan 6y agoThen why not use libraries like io-ts [0] to define interfaces, which survive the compilation, can test untyped objects against the given schema and could also be used as DI tokens. Still, depending on structural typing here feels like a hack, but I never did this so maybe someone with experience in a large codebase can chime in. Anyway, IMHO, Typescript isn't designed for dependency injection in mind. Microsoft also has a DI library [1] but it feels like too much wiring to compensate for the lack of compiled interfaces. [0]: https://github.com/gcanti/io-ts https://github.com/gcanti/io-ts [1]: https://github.com/Microsoft/tsyringe https://github.com/Microsoft/tsyringe
- nobleach 6y agoI'd say that tsyringe is about the same level of "wiring" that one would see with a Nest.JS module. The major difference being it handles the implicit wiring a bit better. Nest.JS will freak out if you don't explicitly tell it what to do. (could be a good thing?)