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
答案 0 :(得分:-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);
}