Angular 2指南教程di上的奇怪打字条继承



在Angular 2指南依赖注入(在第一章中中,为什么依赖注入?)有一些奇怪的代码行。他们工作,但我不知道为什么。您还可以在https://angular.io/resources/live-examples/depparendency-invoction/ts/eplnkr.html。

上找到运行示例。

在文件

export class Engine { 
  public cylinders = 4; 
}
export class Car {
  public description = 'DI';
  constructor(public engine: Engine, public tires: Tires) { }
  ...
}

在文件 car-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;
}

它可以通过打字稿编译器而无需警告或错误。

奇怪!为什么可以使用错误的引擎类型创建汽车?
new Engine2(...)从类引擎中创建一个不是从类引擎派生的对象。

这种行为是tumpecript的错误还是功能?

我希望文件 car-creation.ts

中的代码以下行
class Engine2 extends Engine {
  constructor(public cylinders: number) {
    super();
  }
}

...或...

class Engine2 extends Engine {
  constructor(cylinders: number) {
    super(); 
    this.cylinders = cylinders;
  }
}

打字稿使用结构键入而不是标称键入。您可以在此处找到有关该主题的更多信息。即使您正在编写class,也不是班级诊断意义上的班级。这只是创建原型的语法糖。

class Engine2 {
  constructor(public cylinders: number) { }
}
class Engine { 
  public cylinders = 4; 
}

即使它们没有彼此继承,它们在结构层面上也是如此。两者都有public成员cylinders,即number。虽然Engine总是有4个气缸,但您可以用任何数量的气缸启动Engine2

编写像constructor(public cylinders: number) {}这样的构造函数是用于初始化公共成员的语法糖。

最新更新