San*_*jay 2 javascript interface class typescript
我有以下非常基本的代码:
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`
}
}
Run Code Online (Sandbox Code Playgroud)
现在,打字稿不允许我在界面中创建私有属性。但是,由于某种原因,如果我在具有私有属性的类中实现该接口,它会抛出Class 'EmployeeSalary' incorrectly implements interface 'EmployeeSalaryInterface'. Property 'name' is private in type 'EmployeeSalary' but not in type 'EmployeeSalaryInterface'.ts(2420)
如果打字稿不允许在接口中包含访问修饰符那么它为什么会抱怨呢?
接口是一个公共协议。“类 A 实现接口 B”的意思是:“类 A 的任何实例都发布接口 B 中的所有属性和方法,因此任何使用实例的人都可以使用它们”。
所以,在你的情况下打字稿行为是正确的