简体   繁体   English

继承方法调用触发Typescript编译器错误

[英]Inheritance method call triggers Typescript compiler error

I am having an issue with webstorm typescript compiler. 我在使用webstorm打字稿编译器时遇到问题。 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 typing "super", I see all rootData public methods in the intellisense. 因此,键入“ super”,我会在智能感知中看到所有rootData公共方法。 But after setting super.insert(), I get the following error : 但是在设置super.insert()之后,出现以下错误:

TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword TS2340:仅可通过'super'关键字访问基类的公共和受保护的方法

Tried in TS playground, it is working (simplified version thought). 在TS游乐场中尝试过,它正在工作(认为是简化版本)。

Thanks for your help. 谢谢你的帮助。

EDIT: After checking the compiled javascript, the call of the super method is there. 编辑:检查编译的javascript后,超级方法的调用在那里。 So the compiler gives an error but compiles... 所以编译器给出了一个错误,但是编译了……

Because super calls are redirected to the prototype you cannot use a property and need to use a method ie can't use = ()=> . 因为super调用被重定向到prototype您不能使用property而需要使用method即不能使用= ()=>

Fixed code: 固定代码:

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

  constructor(){
    //...
  }

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

class child extends rootData {
  //...   

  constructor(){
     super();
  }

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

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 . 您可以在此处查看它的TypeScript Playgound版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM