【问题标题】:Declaring properties in parent class that are defined in child class in TypeScript在 TypeScript 的子类中定义的父类中声明属性
【发布时间】:2019-05-02 18:16:45
【问题描述】:

一个简单的例子来说明我的问题:

class Animal {
  foo() {
    console.log(this.bar);
  }
}

class Dog extends Animal {
  bar: string;
  constructor() {
    super();
    this.bar = "bar";
  }
  test() {
    this.foo();
  }
}

new Dog().test();

TypeScript 错误:

类型“Animal”.ts 上不存在属性“bar”

我知道需要在 Dog 类中声明 bar 属性,但 TypeScript 也希望我在 Animal 类中声明它。这是预期的吗?继承时是否需要从 Child -> Parent 类中复制属性声明?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    继承时是否需要从 Child -> Parent 类中复制属性声明?

    没有。将 bar 移动到 Animal 类。

    或者使用类型保护:

     if(this instanceof Dog)
       console.log(this.bar);
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2017-12-31
      • 2018-12-05
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      相关资源
      最近更新 更多