Inheritance method call triggers Typescript compiler error

后端 未结 2 1718
陌清茗
陌清茗 2020-12-18 00:30

I am having an issue with webstorm typescript compiler. I have the following classes

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

  constructor(){
    //...
         


        
相关标签:
2条回答
  • 2020-12-18 00:50

    You could create an "internal" method that is protected that actually performs the logic. Since you can't call it outside of the class, the this 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 a TypeScript Playgound version of it here.

    0 讨论(0)
  • 2020-12-18 00:53

    Because super calls are redirected to the prototype you cannot use a property and need to use a method i.e. can't use = ()=>.

    Fixed code:

    export class rootData{
      id:string
      //...
    
      constructor(){
        //...
      }
    
      insert():Promise<any>{
        //...
      }
    }
    
    class child extends rootData {
      //...   
    
      constructor(){
         super();
      }
    
      insert():Promise<any> {
            return super.insert();
        }
    }
    
    0 讨论(0)
提交回复
热议问题