How to correctly 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?
But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use. Therefore, the abstract method cannot be private.
Implementation of Abstract Classes in TypeScriptThe function Object() { [native code] } declares the firstName and lastName attributes in the Employee class. The method getStipend() is an abstract method. The logic will be implemented in the derived class based on the employee type.
abstract class Person { name: string; constructor(name: string) { this.name = name; } display(): void{ console. log(this.name); } abstract find(string): Person; } class Employee extends Person { empCode: number; constructor(name: string, code: number) { super(name); // must call super() this.
TypeScript has the ability to define classes as abstract. This means they cannot be instantiated directly; only nonabstract subclasses can be.
Quick aside, isCitrus
should be this.isCitrus
. On with the main show...
Abstract methods must be visible to sub-classes, because you are requiring the sub-class to implement the 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, don't declare it on 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())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With