如何将一个 class 注入另一个以用作 es6 classes 中的构造函数

How to inject one class into another for use as a constructor in es6 classes

我有一个我想使用的名为 pigpio 的模块,它导出一个名为 Gpio

的 class

我想将此 class 作为依赖项注入另一个 class 以便我可以使用它来构建 GPIO 实例:

// a simplified example of the class

import { Gpio } from "pigpio";

class PinManager {

    gpioBuilder: Gpio
    construct(builder: Gpio){
        this.gpioBuilder = builder
    }

    buildNewGpioPin(pinNumber: number, direction: number){
        return new this.gpioBuilder(pinNumber, direction)
    }
}

export default PinManager

问题是,当我尝试调用 this.gpioBuilder 来构造 Gpio class 的新实例时,我收到一条错误消息,告诉我 class 没有构造函数在 属性:

我确定这是因为 es6 classes 只是 javascript 原型继承模式的语法糖,但我不确定如何解决这个问题。

我想将 Gpio 作为依赖项注入,以便在测试中更容易模拟,但如果我不能以这种方式进行依赖项注入,我不确定该怎么做。

更新post正确答案

在 Alex 给出的示例之后,我能够更正我的 class 并消除错误:

import { Gpio } from "pigpio"

class PinManager {
    gpioBuilder: typeof Gpio
    construct(builder: typeof Gpio) {
        this.gpioBuilder = builder
    }

    buildNewGpioPin(pinNumber: number, direction: number) {
        return new this.gpioBuilder(pinNumber, { mode: direction })
    }
}

export default PinManager

我还回顾了 typescript 手册,以解释为什么这样做(我一直在阅读手册但没有看到它,结果我还没有读到那部分):

https://www.typescriptlang.org/docs/handbook/classes.html#constructor-functions

重要的部分是:

... Here we use typeof Greeter, that is “give me the type of the Greeter class itself” rather than the instance type. Or, more precisely, “give me the type of the symbol called Greeter,” which is the type of the constructor function. ...

再次感谢您的帮助!!

当您使用 class 作为类型时,typescript 将其解释为 class 的实例,而不是 class 构造函数。如果需要构造函数,可以使用 typeof MyClass

所以听起来您想键入 gpioBuilder 作为 class 构造函数类型 typeof Gpio

import { Gpio } from "pigpio";

class PinManager {

    gpioBuilder: typeof Gpio
    constructor(builder: typeof Gpio){
        this.gpioBuilder = builder
    }

    buildNewGpioPin(pinNumber: number, direction: number){
        return new this.gpioBuilder(pinNumber, direction)
    }
}

export default PinManager

Playground