Typescript: (intermediate value).(...) is not a function when call a method of parent class from derived class

Viewed 1255

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?

1 Answers

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--;
    }
}
Related