为什么我在添加一些protected
访问修饰符时出错?
如果使用private
,一切正常!
export interface IFighter {
readonly _name: string;
protected _health: number; // [ts] 'protected' modifier cannot appear on a type member.
_power: number;
health: () => number;
name: () => string;
setDamage: (damage: number) => void;
hit: (enemy: Fighter, point: number) => void;
knockout: () => Promise<any>;
}
export class Fighter implements IFighter { // Class 'Fighter' incorrectly implements interface 'IFighter'.
// Property '_health' is protected in type 'Fighter' but public in type 'IFighter'.
_name: string;
protected _health: number;
_power: number;
constructor(name: string, health: number, power: number) {
this._name = name;
this._health = health;
this._power = power;
}
health(): number {
return this._health;
}
name(): string {
return this._name;
}
setDamage(damage: number): void {
this._health = this._health - damage;
console.log(`${this._name} got ${damage} dmg. ${this._health}hp less`);
}
hit(enemy: Fighter, point: number): void {
let damage: number = point * this._power;
enemy.setDamage(damage);
}
knockout(): Promise<any> {
return new Promise((resolve, reject) => {
console.log("time is over");
setTimeout(() => {
resolve(() => {});
}, 500);
});
}
}
答案 0 :(得分:0)
Interface的基本逻辑是像 Public Contract 或架构那样工作,因此我们可以在其他对象上使用它,同时保持一定数量的必需功能或属性。
对于您来说, IFighter 是一个接口,因此,它不能将其属性声明为受保护的。否则,它将失去使用接口的目的。
您应该从接口中删除受保护的对象,然后在类本身中声明它。