I'm currently facing a challenge solving an abstract class problem with Typescript. Let me explain what I am trying to accomplish.
There is a class named Sword
that extends Weapon
. Each Weapon
must have certain properties like the damage
, but since each weapon type inflicts different levels of damage (for example, a sword may deal 1 damage while a bow deals 2 damage), I need to define specific properties in the Sword
class. Here's how my script looks:
abstract class Weapon
{
protected abstract damage: number;
constructor() {
alert(this.damage);
}
showDamage() {
alert(this.damage);
}
}
class Sword extends Weapon implements WeaponInterface {
protected damage: number = 999;
constructor() {
super();
}
}
const sword = new Sword;
sword.showDamage();
When running this script on
http://www.typescriptlang.org/play/
, I receive two messages:
undefined
999
I'm unsure why the Weapon.constructor
gets executed first. This seems to defeat the purpose of declaring an abstract value. If I have to use super(this.damage)
to pass it into the Weapon
class, there doesn't seem to be a need for protected abstract damage
.
If I can't even establish basic inheritance in Typescript, why does it offer support for abstract classes? It forces me to do new Weapon(new Sword)
, making it impossible to typehint a SwordInterface
on other classes like Inventory
.
class Inventory
{
// Assuming we are equipped with a "Shield," we can only equip items of type "Sword"
addSword(sword: SwordInterface): void {
}
}
As someone new to compiled languages and Typescript, I'm seeking guidance on the proper way to achieve this without resorting to passing class properties into the super()
call.
I want to maintain inheritance and interfaces without any disruptions.