Typescript Inheritance Method Call Method Compiler Error

I have a problem with the webstorm typescript compiler. I have the following classes

export class rootData{
  id:string
  //...

  constructor(){
    //...
  }

  insert = ():Promise<any> =>{
    //...
  }
}

class child extends rootData {
  //...   

  constructor(){
     super();
  }

  insert = ():Promise<any> => {
        return super.insert();
    }
}

      

So by typing "super" I can see all the public rootData methods in intellisense. But after installing super.insert (), I get the following error:

TS2340: Only public and protected methods of the base class are available using the 'super' keyword

Tried on TS playground, it works (thought of simplified version).

Thank you for your help.

EDIT: After checking the compiled javascript, there is a super method call. So the compiler gives an error but compiles ...

+3


source to share


2 answers


Since calls are super

redirected to prototype

, you cannot property

and must use method

, that is, you cannot use = ()=>

.

Fixed code:



export class rootData{
  id:string
  //...

  constructor(){
    //...
  }

  insert():Promise<any>{
    //...
  }
}

class child extends rootData {
  //...   

  constructor(){
     super();
  }

  insert():Promise<any> {
        return super.insert();
    }
}

      

+12


source


You can create an "internal" method that is protected that actually executes the logic. Since you cannot call it outside of the class, it will always be in the correct context.

export class rootData{
  id:string
  //...

  constructor(){
    //...
  }

  insert = ():Promise<any> =>{
    return this.insertInternal();
  }

  protected insertInternal():Promise<any>{
    //...
  }
}

class child extends rootData {
  //...   

  constructor(){
     super();
  }

  protected insertInternal():Promise<any> {
        return super.insertInternal();
    }
}

      



You can view the TypeScript Playgound version here .

0


source







All Articles