typescript - ts 实例化作为参数传递的类
我在尝试实现一种整洁的方式来建造多个植物(灵感来自植物大战僵尸)。为了方便添加更多植物类型,我想让植物的成本和伤害静态化,这样我可以为该类型的所有植物只设置一次。
在这种情况下,我只有一种植物(向日葵),现在我想实例化向日葵植物。在 Cell 类的 build 方法中。
当我这样做时,我会收到错误:Cannot create an instance of an abstract class.,这对我来说是可以理解的。那么,有没有办法只允许传递继承自 Plant 的非抽象类作为 build() 方法的参数,或者我必须实现某种 if (!c isAbstract) 检查呢?
abstract class Plant {
public static dmg: number;
public static cost: number;
constructor(cell: Cell) {
this.cell = cell;
}
cell: Cell;
}
// I would like to create more Plants like this
class Sunflower extends Plant {
public static dmg = 0;
public static cost = 50;
cell: Cell;
constructor(cell: Cell) {
super(cell);
}
}
class Cell {
build(c: typeof Plant) {
if (c.cost <= game.money) {
this.plant = new c(this); //Cannot create an instance of an abstract class.
game.money -= c.cost;
}
}
}
// this is how I would build plants.
let c = new Cell();
c.build(Sunflower);
答案#1
你可以这样做:
class Cell {
build<T extends Plant>(plant: (new (cell:Cell) => T)) {
const plantInstance = new plant(this);
}
}
游乐场链接
