如何使用Typescript和NodeJS将模块注入类中

How to inject a module into a class using Typescript and NodeJS

本文关键字:模块 注入 NodeJS 何使用 Typescript      更新时间:2023-09-26

我在nodeJS+Typescript中进行开发。我有OO背景,我想从nodejs模块中受益,但我很难将它们与不应该是模块的类混合在一起。

这就是我要做的:

foo.ts(模块)

import http = require("http")
export class Foo {
    public fooMethod() : number { ... }
}

bar.ts(不应该是一个模块)

namespace Ns {
    export class Bar {
        constructor(private foo: Foo) { ... } //"Foo" is not being found by the intellisense
        public barMethod() : number { 
            return this.foo.fooMethod()
        }
    }
}

server.js(节点启动文件)

var Foo = import("./foo");
var foo = new Foo();
foo.configure(...)     //Configure foo before inject it into bar
var bar = new Ns.Bar(foo)

当我试图像这样构建代码时,我面临的问题:

  1. Bar看不到Foo。我试图添加对该文件的引用,但没有成功
  2. 当我导入时,它"起作用"/foo,但当我这样做时,Bar在同一命名空间上定义的其他文件中看不到其他导出的类型(即使我写了类型的全名,即包含命名空间,它仍然看不到)
  3. 因此,我删除了Bar中的命名空间Ns,当我用命名空间键入它的名称时,我可以看到其他类型。但现在Bar是一个模块,我感觉我的构造函数注入有味道,因为Foo是导入的,我可以直接实例化它

我不想强求我的标准。我想知道什么是我正在尝试做的事情的正确方法。这种斗争让我觉得在开发nodejs应用程序时,我有义务重新设计并使用完整的模块。是这样吗?

如果我应该使用完整的模块,我应该如何管理依赖项注入?

感谢

要充分利用OOP(或者更好地说是基于接口的编程或面向协议的编程)的功能,您应该使用interface Foo来隐藏Bar类对特定实现MyFoo的使用。

Foo.ts

export interface Foo {
  fooMethod(): number;
}

MyFoo.ts

export class MyFoo {
  fooMethod(): number {
    return 1;
  }
}

Bar.ts

import {Foo} from './Foo'
export class Bar {
  constructor(private foo: Foo) {}
  barMethod(): number {
    return this.foo.fooMethod();
  }
}

其他地方:

import {Boo} from './Boo'
import {MyFoo} from './MyFoo'
const result = new Boo(new MyFoo()).barMethod();

就我个人而言,我不建议使用名称空间。您可以在这里阅读更多关于名称空间和模块的信息。