Home > Software engineering >  Reference Error: calling class method in super() typescript
Reference Error: calling class method in super() typescript

Time:09-03

I am not able to call someMethod, it gives error

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor\

class BaseClass{
//some properties here I want to return whoever extends BaseClass
}

class ChildClass extend BaseClass{
    constructor(){
        super(
            this.someMethod();
        )
    }
    
    someMethod() {}
}

CodePudding user response:

In your constructor, you have to call super() before you can use this:

class BaseClass{
//some properties here I want to return whoever calls ChildClass
}

class ChildClass extend BaseClass{
    constructor(){
        super()
        this.someMethod();
    }
    
    someMethod() {}
}

There is no permitted structure for super(this.someMethod()) because you can't use this before you've called super(...). There is something like super.someMethod() which lets you call base class methods (without your local override), but that's not a substitute for calling super() in your constructor.

You can call super(someArgs) with arguments if you want and that would be whatever arguments you want to be passed to the base class constructor. But, you can't use this before doing so.

  • Related