elmi
elmi

Reputation: 184

Typescript: Calling the arrow function of a child class in an abstract parent class throws an error

Here is the simple code. I need to use arrow function hello() for reasons in the child class.

The code throws an error when I call the.greeting() in the constructor of the parent class:

index.ts:29 Uncaught TypeError: this.hello is not a function at Child.greeting ...

However, the problem does not occur when I use the regular function, but I must use the arrow function.

Please tell me what the problem is and how to fix it.

abstract class Parent{
    constructor(){
      this.greeting();
    }

    abstract hello();

    greeting(){
        this.hello();
    }
}


class Child extends Parent{
  hello = ()=>{
        console.log('hello there');
    }
}

const child = new Child();

Upvotes: 1

Views: 726

Answers (1)

Royston Shufflebotham
Royston Shufflebotham

Reputation: 970

The way the hello property in Child works is effectively by the language adding a constructor to Child which says:

constructor() {
  this.hello = () => ...
}

That Child constructor doesn't run until the Parent constructor has finished, so at the point the Parent constructor is running, hello hasn't yet been assigned. So that's why it blows up. (Some other languages prevent you from calling virtual methods from inside a base class constructor for the same reason.)

(Why do you 'need' to make hello an arrow function?)

Fixing it is a little tricksy. If you want it to be callable from the Parent constructor, you simply can't make it an arrow function immediately.

Presumably you need to use an arrow function because you sometimes want hello to work as a separable function (i.e. called as a plain method without being a function)? If so, you could simply bind it on use, by using child.hello.bind(child) when you need that.

Upvotes: 2

Related Questions