admin管理员组

文章数量:1323370

This my parent class, it has trigger method which is public method:

class BaseEffect {
    //properties and contructor...
    //other methods...

    public trigger = (): void => void (this.target.hitPoint -= this.amount);
}

And a TurnBasedEffect extends BaseEffect class:

class TurnBasedEffect extends BaseEffect {
    //properties and contructor...
    //other methods...

    public trigger = (): void => {
        super.trigger();
        this.remainingTurns--;
    };
}

This class also has trigger method, inside this method, a trigger method of the parent class is called.

The problem is when a trigger method of the derived class is called, typescript throws this error:

TypeError: (intermediate value).trigger is not a function

And point to this line of the trigger method of the TurnBasedEffect class:

//...
super.trigger();
//...

What's wrong with my classes and how to solve this problem?

This my parent class, it has trigger method which is public method:

class BaseEffect {
    //properties and contructor...
    //other methods...

    public trigger = (): void => void (this.target.hitPoint -= this.amount);
}

And a TurnBasedEffect extends BaseEffect class:

class TurnBasedEffect extends BaseEffect {
    //properties and contructor...
    //other methods...

    public trigger = (): void => {
        super.trigger();
        this.remainingTurns--;
    };
}

This class also has trigger method, inside this method, a trigger method of the parent class is called.

The problem is when a trigger method of the derived class is called, typescript throws this error:

TypeError: (intermediate value).trigger is not a function

And point to this line of the trigger method of the TurnBasedEffect class:

//...
super.trigger();
//...

What's wrong with my classes and how to solve this problem?

Share Improve this question asked Jun 15, 2020 at 1:51 Trí PhanTrí Phan 1,1933 gold badges16 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You have a field that’s initialized to an arrow function. The initialization is done by the constructor:

class Foo {
    bar = () => {};
}

console.log(new Foo().bar);
console.log(new Foo().hasOwnProperty('bar'));
console.log(Foo.prototype.bar);

The field doesn’t end up in the prototype chain, so it isn’t inherited, and you can’t call it through super.

I suggest writing normal methods:

class BaseEffect {
    //properties and contructor...
    //other methods...

    public trigger() {
        this.target.hitPoint -= this.amount;
    }
}

class TurnBasedEffect extends BaseEffect {
    //properties and contructor...
    //other methods...

    public trigger() {
        super.trigger();
        this.remainingTurns--;
    }
}

本文标签: