Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何将一个类注入另一个类中,以用作es6类中的构造函数_Typescript_Dependency Injection_Es6 Class - Fatal编程技术网

Typescript 如何将一个类注入另一个类中,以用作es6类中的构造函数

Typescript 如何将一个类注入另一个类中,以用作es6类中的构造函数,typescript,dependency-injection,es6-class,Typescript,Dependency Injection,Es6 Class,我想使用一个名为pigpio的模块,它导出一个名为Gpio 我想将该类作为依赖项注入另一个类中,以便使用它构建GPIO实例: // a simplified example of the class import { Gpio } from "pigpio"; class PinManager { gpioBuilder: Gpio construct(builder: Gpio){ this.gpioBuilder = builder

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

我想将该类作为依赖项注入另一个类中,以便使用它构建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类的新实例时,我得到一个错误,告诉我属性中没有该类的构造函数:

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

我想将
Gpio
作为依赖项注入,这样在测试中更容易模拟,但是如果我不能用这种方式进行依赖项注入,我不完全确定如何进行

更新帖子正确答案 在Alex给出的示例之后,我能够更正我的类并消除错误:

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手册,以了解其工作原理(我一直在阅读手册,但没有看到,结果我只是还没有了解到这一部分):

重要的部分是:

。。。这里我们使用typeof Greeter,即“给我Greeter类本身的类型”,而不是实例类型。或者,更准确地说,“给我一个称为Greeter的符号类型”,这是构造函数的类型


再次感谢你的帮助

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

因此,听起来您希望键入
gpioBuilder
作为类构造函数类型
typeofgpio

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

:我整天都在琢磨测试和注入问题,这100%解决了这个问题。非常感谢。我从来没有这么高兴地给你打勾:P