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