TypeScript错误-可通过'super'关键字访问TS2340公共方法 [英] TypeScript error - TS2340 public methods accessible via 'super' keyword

查看:642
本文介绍了TypeScript错误-可通过'super'关键字访问TS2340公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 5中有一个带有抽象类和接口的长继承链。它引发错误错误TS2340:只有基类的公共方法和受保护方法可以通过'super'关键字访问。 / code>

I have a long inheritance chain with abstract classes and interfaces in Angular 5. It's throwing an error error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword.

抽象父类的方法定义为:

The abstract parent class has the method defined as:

public get text() {
    return this.el.attr('text/text').replace("\n", "");
} 

子类的方法定义为:

public get text(): string {
  return super.text;
}

如何让子类不抛出TS2340错误?

How do I get the child class to not throw the TS2340 error?

我创建了一个展示问题的stackblitz:

I've created a stackblitz that demonstrates the problem:

https://stackblitz.com/edit/ts2340-super-keywork-public?file=app%2Fnodes .ts

推荐答案

这是一个糟糕的错误消息,但重要的是不要忽略它!

This is a lousy error message, but very important not to ignore it!

导致我出现此错误的代码如下:

My code that led me to this error was as follows:

private _name: string;
public get name(): string { return this._name; }
public set name(name: string) { this._name = name; }



SubTracker.ts(扩展跟踪器)



SubTracker.ts (extends Tracker)

super.name = "Simon";   // seems innocuous enough right? 

然后我得到了错误:


错误TS2340:只有基类的公共方法和受保护方法才可以通过'super'关键字访问

error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword.

执行 super.name 时,实际上是在超类上覆盖实现本身。因此,我仅成功地将 name 转换为全局静态属性。然后在任何地方,我都将访问名称,我将获得设置为该值的最后一个值。

Turns out when you do super.name you are actually overwriting the implementation itself on the super class. So I only succeeded to convert name into a global static property. Then anywhere I would access name I'd get the last value I'd set it to.

this.name = "Simon";

所以不要忽略此编译器错误!

So don't ignore this compiler error!

这篇关于TypeScript错误-可通过'super'关键字访问TS2340公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆