1

I was trying to implement a neat way to build multiple Plants (inspired by plants vs zombies). To make it easy to add more plant Types I wanted to make the cost and dmg of the plant static so I can set it once for all Plants of this type.

In this case I have only one Plant (Sunflower), now I would like to instantiate the Sunflowerplant. In the build method in the Cell class.

When doing it like this I get the error: 'T' only refers to a type, but is being used as a value here.

Is there a way to create an instance of the Plant like this:

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 {
  // I would like to create Plants like this
  build<T extends Plant>() {
    if (T.cost <= game.money) {  //'T' only refers to a type, but is being used as a value here.
      this.plant = new T(this);  //'T' only refers to a type, but is being used as a value here.
      game.money -= T.cost;      //'T' only refers to a type, but is being used as a value here.
    }
  }
}

// this is how I would build plants.
// altho I am not sure yet how to change Plant types using an UI with this aproach. 
let c = new Cell();
c.build<Sunflower>();
0brine
  • 450
  • 5
  • 18
  • 1
    `T` in `build` method lives in a different scope. It is erased during typescript compilation. It means that you are not allowed to treat types as a runtime value. Treat them as a jsdoc or just a useful comment but not as a value – captain-yossarian from Ukraine Feb 09 '22 at 11:08
  • 2
    What the previous comment said. ^ You can change your interface to `c.build(Sunflower)` instead. – ndnenkov Feb 09 '22 at 11:34

0 Answers0