如何在TypeScript中正确定义私有抽象方法?
这是一个简单的代码:
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())
}
}
此代码不起作用。如何解决?
答案 0 :(得分:11)
快一点,isCitrus
应为this.isCitrus
。在主要节目......
抽象方法必须对子类可见,因为您需要子类来实现该方法。
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())
}
}
如果您希望该方法真正私有,请不要在基类上声明它。
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())
}
}