覆盖父类属性的属性类型

时间:2020-07-25 04:39:45

标签: typescript

在代码片段中,我用一个类型为Child的新对象(是Parent的子类)覆盖了Parent类型的foo属性。我应该完全这样做吗?

当我在AnotherChild类中构造foo属性时,在创建Child对象之前,this.foo的类型为Parent。创建Child对象之后,this.foo的类型将更改为Child。我不确定这是否是个好习惯。

class Parent {
  constructor(public x, public y){}
}

class Child extends Parent {}

class AnotherParent {
  public foo: Parent;
  constructor() {
    this.foo = new Parent(1,2);
  }
}

class AnotherChild extends anotherParent {
  public foo: Child;
  super();
  this.foo = new Child(this.foo.x, this.foo.y);
}

0 个答案:

没有答案