【问题标题】:Inheritance method call triggers Typescript compiler error继承方法调用触发 Typescript 编译器错误
【发布时间】:2015-09-14 08:07:18
【问题描述】:

我遇到了 webstorm typescript 编译器的问题。我有以下课程

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

  constructor(){
    //...
  }

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

class child extends rootData {
  //...   

  constructor(){
     super();
  }

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

所以输入“super”,我会在智能感知中看到所有 rootData 公共方法。但是在设置 super.insert() 之后,我得到以下错误:

TS2340:只能通过“super”关键字访问基类的公共和受保护方法

在 TS 操场上尝试过,它正在工作(简化版思想)。

感谢您的帮助。

编辑:检查编译的javascript后,超级方法的调用就在那里。所以编译器给出了错误但编译...

【问题讨论】:

    标签: javascript node.js typescript webstorm


    【解决方案1】:

    因为super 调用被重定向到prototype,所以您不能使用property,需要使用method,即不能使用= ()=&gt;。

    固定代码:

    export class rootData{
      id:string
      //...
    
      constructor(){
        //...
      }
    
      insert():Promise<any>{
        //...
      }
    }
    
    class child extends rootData {
      //...   
    
      constructor(){
         super();
      }
    
      insert():Promise<any> {
            return super.insert();
        }
    }
    

    【讨论】:

    • 我也遇到了这个问题。感谢您发布此信息。不幸的是 TypeScript 的设计,因为我在我的对象成员定义中使用 '=>' 来确保捕获 'this' 而不必在每次需要对对象进行操作的成员函数时调用 bind()。所以现在我有这种丑陋,所有函数都在使用 => 并捕获它,除了碰巧在覆盖中使用的函数,它们需要 bind()。这会创建非常丑陋和令人困惑的代码。似乎有更好的方法来进行超级调用,而不是简单地禁止'=>'。
    • @basarat 请保持诚实,如果我的回答也无效,请告诉我。
    • 关于上面发布的关于在使用此方法时需要bind() 的问题,请参阅the typescript book(由此处的回答者编写!)了解如何解决该需要@user2080225
    • 类属性在哪里?它们不是位于原型中吗?如何访问它们?
    • FWIW,如果 Typescript 目标 = es2015 或更高版本,此答案对我有用。它不适用于es5。
    【解决方案2】:

    您可以创建一个受保护的“内部”方法来实际执行逻辑。由于您不能在课堂外调用它,因此 this 将始终位于正确的上下文中。

    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();
        }
    }
    

    您可以查看它的 TypeScript Playgound 版本here。

    【讨论】:

      猜你喜欢
      • 2017-11-21
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多