How to declare a private abstract method in TypeScript?

How to define private abstract methods in TypeScript?

Here is a simple code:

abstract class Fruit { name: string; constructor (name: string) { this.name = name } abstract private hiFrase (): string; } class Apple extends Fruit { isCitrus: boolean; constructor(name: string, isCitrus: boolean) { super(name); this.isCitrus = isCitrus; } private hiFrase(): string { return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (isCitrus ? "" : " not ") + "citrus"; } public sayHi() { alert(this.hiFrase()) } } 

This code does not work. How to fix it?

+5
source share
1 answer

Rather, isCitrus should be this.isCitrus . On the main show ...

Abstract methods must be visible to subclasses because you require the subclass to execute this method.

 abstract class Fruit { name: string; constructor (name: string) { this.name = name } protected abstract hiFrase(): string; } class Apple extends Fruit { isCitrus: boolean; constructor(name: string, isCitrus: boolean) { super(name); this.isCitrus = isCitrus; } protected hiFrase(): string { return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (this.isCitrus ? "" : " not ") + "citrus"; } public sayHi() { alert(this.hiFrase()) } } 

If you want the method to be truly private, do not declare it in the base class.

 abstract class Fruit { name: string; constructor (name: string) { this.name = name } } class Apple extends Fruit { isCitrus: boolean; constructor(name: string, isCitrus: boolean) { super(name); this.isCitrus = isCitrus; } private hiFrase(): string { return "Hi! I\'m an aplle and my name is " + this.name + " and I'm " + (this.isCitrus ? "" : " not ") + "citrus"; } public sayHi() { alert(this.hiFrase()) } } 
+5
source

Source: https://habr.com/ru/post/1260704/


All Articles