有没有办法使用typescript

时间:2017-03-09 21:14:27

标签: dependency-injection typescript2.0

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

Supplied parameters do not match any signature of call target

并且在出现此错误时正在执行

我的基类:

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

我的班级使用电机

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等任何库或模块,我只是想知道如何在没有它们的情况下实现

1 个答案:

答案 0 :(得分:0)

您有此错误,因为您未在Vehiculo类型上指定构造函数。

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

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;
        }
    }
}