打字稿中的封闭(依赖注入) [英] Closures in Typescript (Dependency Injection)
问题描述
我正在尝试使用带有依赖项的功能样式的TypeScript。假设我想创建一个依赖于另一个模块的模块。
如果我不使用依赖注入,它看起来像这样(在节点中)。
SomeOtherModule = require(SomeOtherModule)
exports.doSomething = function(){
SomeOtherModule.blah()
}
这就是我如何使用依赖注入来实现的。
函数doSomething(){
SomeOtherModule.blah()
}
return {doSomething:doSomething};
在打字稿中,如果你定义了一个具体的类或模块,你可以直接键入函数当你输出他们或包括他们在课堂上。彼此相邻。
但是由于我不能在DI函数中定义一个模块,所以唯一能做到的方法就是定义我单独返回的对象的接口,这很烦人,因为我想让类型注释符合定义。
有什么更好的方法可以做到这一点? 我结束了在我的项目中放弃了AMD,因为我也在使用AngularJS,并且他们踩在彼此的脚趾上。我一直使用相同的DI模式,所以最终看起来像这样。
我对此很满意。我尝试使用类来代替(如果保持模块无状态并使构造函数成为注入函数,则可以非常接近),但我不喜欢使用 this
所有的依赖关系。另外,类实际上并没有给我买任何东西,因为如果我编码到一个接口,我不得不两次定义类型。
界面IMyService {
doSomething();
module.exports = function(SomeOtherModule){
return {doSomething:doSomething}
函数doSomething(){
SomeOtherModule.blah()
}
}
I'm getting my butt kicked trying to use TypeScript in a functional style with dependencies. Let's say I want to make a module that depends on another module.
If I wasn't using Dependency Injection it would look like this (in node).
SomeOtherModule = require("SomeOtherModule")
exports.doSomething = function() {
SomeOtherModule.blah()
}
This is how I do it with Dependency Injection
module.exports = function(SomeOtherModule) {
function doSomething() {
SomeOtherModule.blah()
}
return {doSomething: doSomething};
}
In typescript if you define a concrete class or module you can just type the functions as you export them or include them in the class. It's all right next to each other.
But since I can't define a module inside the DI function, the only way to do this that I can see would be to define an interface for the object I'm returning separately, which is annoying, because I want to have the type annotations in line with the definitions.
What's a better way to do this?
解决方案 I ended up dropping AMD on my project, since I'm also using AngularJS and they step on each other's toes. I did keep using that same DI pattern through, so it looks like this in the end.
I'm pretty happy with it. I experimenting uses classes instead (you can get really close if you keep your module stateless and have the constructor be the injector function), but I didn't like having to use this
for all the dependencies.
Also, classes don't actually buy me anything, because if I were coding to an interface I'd have to define the types twice anyway.
interface IMyService {
doSomething();
}
module.exports = function(SomeOtherModule) {
return {doSomething: doSomething}
function doSomething() {
SomeOtherModule.blah()
}
}
这篇关于打字稿中的封闭(依赖注入)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!