我有以下非常基本的代码:
interface EmployeeSalaryInterface {
name: string
hoursWorked: number
readonly perHourRate: number
calculateSalary(): string
}
class EmployeeSalary implements EmployeeSalaryInterface {
private readonly perHourRate: number = 20
constructor(private name: string, private hoursWorked: number) {}
public calculateSalary(): string {
return `Employee ${this.name} has a base salary of $${this.hoursWorked * this.hoursWorked} for working ${this.hoursWorked} a day`
}
}
现在,打字稿不允许我在界面中创建私有属性。但是,由于某种原因,如果我在具有private属性的类中实现该接口,它将抛出Class 'EmployeeSalary' incorrectly implements interface 'EmployeeSalaryInterface'. Property 'name' is private in type 'EmployeeSalary' but not in type 'EmployeeSalaryInterface'.ts(2420)
如果打字稿不允许在界面中包含访问修饰符,那为什么会抱怨呢?
答案 0 :(得分:1)
接口是公共协议。语句“类A实现接口B”的意思是:“类A的任何实例发布来自接口B的所有属性和方法,因此使用实例的任何人都可以使用它们”。
所以,在您的情况下,打字稿的行为是正确的