I have 2 immutable classes which extends an abstract class which looks as follows:
abstract class Enemy {
abstract readonly attackPower: number;
constructor(
public readonly health: number
) {
}
abstract hit(): Enemy;
}
class Boss extends Enemy {
attackPower = 100;
hit(): Boss {
return new Boss(this.health - 1);
}
}
class NormalEnemy extends Enemy {
attackPower = 5;
hit(): NormalEnemy {
return new NormalEnemy(this.health - 1);
}
}
Note these are immutable classes, so all properties are read-only.
As you can see the "hit" method is being repeated.
Ideally I would like to move to logic to the Enemy abstract class to something like:
abstract class Enemy {
abstract readonly attackPower: number;
constructor(
public readonly health: number
) {
}
hit() {
return new self(health - 1); // not valid TypeScript code
}
}
class Boss extends Enemy {
attackPower = 100;
}
class NormalEnemy extends Enemy {
attackPower = 5;
}
However this is of course not valid.
Anyway to solve this issue?
1?hit(attack: number)