有没有办法使用打字稿使用依赖注入

is there a way to use dependencies injection using typescript

我对此比较陌生,所以我想使用 typescript 实现依赖注入(这是我第一次使用这种模式),我更喜欢使用像 java 或 c# 这样的语言编程OOP,所以更容易应用这种模式, 我在互联网上找到了一个示例,我可以在 eclipse 和 visual studio 上毫无问题地使用它,但是当我在 typescript 上使用它时,IDE 会引发这样的错误:

Supplied parameters do not match any signature of call target

并且在出现此错误时就在实现它的末尾

我的基地class:

class Motor {
    Acelerar(): void {
    }
    GetRevoluciones(): number {
        let currentRPM: number = 0;
        return currentRPM;
    }
}
export {Motor};

我的class使用电机

import { Motor } from "./1";
class Vehiculo {
    private m: Motor;
    public Vehiculo(motorVehiculo: Motor) {
        this.m = motorVehiculo;
    }
    public GetRevolucionesMotor(): number {
        if (this.m != null) {
            return this.m.GetRevoluciones();
        }
        else {
            return -1;
        }
    }
}
export { Vehiculo };

我的界面和电机类型

interface IMotor {
    Acelerar(): void;
    GetRevoluciones(): number;
}
class MotorGasoline implements IMotor {
    private DoAdmission() { }
    private DoCompression() { }
    private DoExplosion() { }
    private DoEscape() { }
    Acelerar() {
        this.DoAdmission();
        this.DoCompression();
        this.DoExplosion();
        this.DoEscape();
    }
    GetRevoluciones() {
        let currentRPM: number = 0;
        return currentRPM;
    }
}
class MotorDiesel implements IMotor {
    Acelerar() {
        this.DoAdmission();
        this.DoCompression();
        this.DoCombustion();
        this.DoEscape();
    }
    GetRevoluciones() {
        let currentRPM: number = 0;
        return currentRPM;
    }
    DoAdmission() { }
    DoCompression() { }
    DoCombustion() { }
    DoEscape() { }
}

这里是出现错误的地方:

import { Vehiculo } from "./2";
enum TypeMotor {
    MOTOR_GASOLINE = 0,
    MOTOR_DIESEL = 1
}
class VehiculoFactory {
    public static VehiculoCreate(tipo: TypeMotor) {
        let v: Vehiculo = null;
        switch (tipo) {
            case TypeMotor.MOTOR_DIESEL:
                v = new Vehiculo(new MotorDiesel()); break;
            case TypeMotor.MOTOR_GASOLINE:
                v = new Vehiculo(new MotorGasoline()); break;
            default: break;
        }
        return v;
    }
}

我暂时不想使用任何库或模块,如 SIMPLE-DIJS 或 D4js 或任何其他,我只想知道没有它们如何实现

出现此错误是因为您没有在 Vehiculo 类型上指定构造函数。

要声明构造函数,您应该使用 constructor 关键字而不是 class 的名称。

class Vehiculo {
    private m: Motor;
    constructor(motorVehiculo: Motor) {
        this.m = motorVehiculo;
    }
    public GetRevolucionesMotor(): number {
        if (this.m != null) {
            return this.m.GetRevoluciones();
        }
        else {
            return -1;
        }
    }
}