在Angular 2 guide Dependency Injection(在第一章为什么依赖注入?)有一些奇怪的代码行。他们工作,但我不知道为什么。您还可以在https://angular.io/resources/live-examples/dependency-injection/ts/eplnkr.html上找到正在运行的示例。Angular 2指南中的奇怪的手稿继承教程DI
在文件car.ts的类引擎和类汽车被声明为:
export class Engine {
public cylinders = 4;
}
export class Car {
public description = 'DI';
constructor(public engine: Engine, public tires: Tires) { }
...
}
在文件汽车creation.ts类汽车使用。 ...
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;
}
}