【问题标题】:Strange Typescript inheritance on Angular 2 Guide Tutorial DIAngular 2 Guide Tutorial DI 上奇怪的 Typescript 继承
【发布时间】: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 Engineclass 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


    【解决方案1】:

    TypeScript 使用 结构类型 而不是名义类型。您可以找到更多关于主题 here 的信息。即使您正在编写class,它也不是类继承意义上的 ... 类。它只是用于创建Prototype 的语法糖。

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

    尽管它们不相互继承,但它们在结构层面上是相同的。两者都有一个public 成员cylinders,即number。虽然Engine 总是有 4 个柱面,但您可以使用任意数量的柱面来初始化 Engine2

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

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2012-11-08
      相关资源
      最近更新 更多