【发布时间】:2017-02-21 15:57:56
【问题描述】:
在Angular 2 guide Dependency Injection(在第一章为什么依赖注入?)有一些奇怪的代码行。他们工作,但我不知道为什么。您还可以在 https://angular.io/resources/live-examples/dependency-injection/ts/eplnkr.html 上找到运行示例。
在文件 car.ts 中,class Engine 和 class Car 声明为:
export class Engine {
public cylinders = 4;
}
export class Car {
public description = 'DI';
constructor(public engine: Engine, public tires: Tires) { }
...
}
在文件 car-creation.ts 中使用了 Car 类 ...
import { Car, Engine, Tires } from './car';
class Engine2 {
constructor(public cylinders: number) { }
}
export function superCar() {
// Super car with 12 cylinders and Flintstone tires.
let bigCylinders = 12;
let car = new Car(new Engine2(bigCylinders), new Tires());
car.description = 'Super';
return car;
}
Typescript 编译器不会出现警告或错误。
奇怪!为什么可以使用错误的引擎类型创建汽车?new Engine2(...) 从类 Engine2 创建一个不是从类 Engine 派生的对象。
这种行为是错误还是 Typescript 的功能?
我希望文件 car-creation.ts 中有以下代码行。
class Engine2 extends Engine {
constructor(public cylinders: number) {
super();
}
}
...或...
class Engine2 extends Engine {
constructor(cylinders: number) {
super();
this.cylinders = cylinders;
}
}
【问题讨论】:
标签: typescript dependency-injection