【问题标题】:Create subclass with a property that is a subclass of that parent's classes corresponding property使用一个属性创建子类,该属性是该父类对应属性的子类
【发布时间】:2017-05-08 23:08:22
【问题描述】:
class TableController {
    constructor(public x,public y){}
}
class Table  {
    public controller = TableController;
}

class SquareTableController extends TableController{
  constructor(public x, public y, public z){
      super(x,y);
      /* do other stuff with z */
  }
}
class SquareTable extends Table{
    public controller = SquareTableController;
}

TypeScript 给我上述代码的以下错误:

TS2415: Class "SquareTable" incorrectly extends base class "Table". 
  Types of property "controller' are incompatible. 
  Type 'typeof SquareTableController' is not assignable to type 'typeof TableController'.

注意 SquareTableController 在其构造函数中有一个额外的参数。

如何在 TypeScript 中进行这样的继承设置?我很确定我在 C# 和 Java 中做过非常相似的事情。

有游乐场here

【问题讨论】:

  • 你到底想在这里做什么?您是否打算引用类 (controller = TableController) 而不是实例 (controller = new TableController())?
  • @NitzanTomer,是的,我故意引用类,而不是类的实例。这是创建 AngularJS 组件时的标准约定
  • 你的代码在操场上编译得很好。
  • 嗯。在操场上为我编译也很好。让我比较一下我项目中的原始版本。 .
  • 现在正在调查。我认为这可能是因为我的 SquareTableController 的构造函数可能与我的 TableController 的构造函数不同

标签: javascript angularjs oop typescript


【解决方案1】:

冒号 : 用于类型注释。

类型注释需要使用冒号:,而不是等号=

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

class Table {
    // type annotation
    public controller: TableController;
}

class SquareTableController extends TableController {
  constructor(public x, public y, public z) {
      super(x, y);
  }
}

// type annotation
class SquareTable extends Table {
    public controller: SquareTableController;
}

等于 =new 用于对象分配。

如果目标是进行赋值而不是类型注释,那么我们可以在调用构造函数时使用等号。

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

class Table {
    // object assignment
    public controller = new TableController(1, 2);
}

class SquareTableController extends TableController {
  constructor(public x, public y, public z) {
      super(x, y);
  }
}

class SquareTable extends Table {
    // object assignment
    public controller = new SquareTableController(1,2,3);
}

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 2020-09-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2011-06-16
    • 2015-10-02
    相关资源
    最近更新 更多