Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript error - TS2340 public methods accessible via 'super' keyword

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", "");
} 

The child class has the method defined as:

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

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

I've created a stackblitz that demonstrates the problem:

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

like image 811
Denise Mauldin Avatar asked May 11 '18 00:05

Denise Mauldin


2 Answers

Unfortunately, this is not supported by TS and by the looks of it, will never be:

https://github.com/Microsoft/TypeScript/issues/338

It seems like the only way to make it work at the moment, is to target ES6 in your compiler options

like image 197
klugjo Avatar answered Nov 03 '22 11:11

klugjo


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

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

Tracker.ts

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

SubTracker.ts (extends Tracker)

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

And then I got the error:

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

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.


So what's the fix? Change super to this:

this.name = "Simon";

So don't ignore this compiler error!

like image 14
Simon_Weaver Avatar answered Nov 03 '22 13:11

Simon_Weaver