|
|
|
|
|
by tunesmith
1373 days ago
|
|
Might as well ask here. On our teams, we have the occasional developer that is insistent on using Typescript in an OO fashion. This has always struck me as square peg round hole. Even though I come from an OO background, Typescript strict settings really seem to push me in a direction of using interfaces and types for type signatures, and almost never classes, subclasses, instantiated objects. I don't have a very good answer for "yeah, but what about dependency injection"? though. Any thoughts from anyone? |
|
There is no "dependency injection" in a functional world, take this opportunity to show your colleague how FP makes their life easier. It's just a function.
Instead of a class, implementing an interface, created by a factory, requiring a constructor, all you need is a function.
Anything that was previously a "dependency" in OO terms is now an argument to your function. If you want to "inject" that dependency you simply partially apply your function, the result is then of course a function with that "dependency" "injected" which can then be used as usual. In JavaScript there's even a nifty built-in prototype method on every function called `Function.prototype.bind` which allows you to do the partial application to create the "dependency injected" function!
Example:
```
const iRequireDependencies = (dependencyA, dependencyB, actualArgumentC, actualArgumentD, ...etc) => console.log(dependencyA, dependencyB, actualArgumentC, actualArgumentD, ...etc);
const withRandomDependencies = iRequireDependencies.bind(undefined, 'randomA', 'randomB')
withRandomDependencies('actualA', 'actualB', 'actualC', 'actualD', 'actualE') // etc
// => 'randomA' 'randomB' 'actualA' 'actualB' 'actualC' 'actualD' 'actualE'
```