我有以下非常基本的代码:
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`
}
}
现在, typescript 不允许我在界面中创建私有(private)属性。但是,由于某种原因,如果我在具有私有(private)属性的类中实现该接口(interface),它会抛出 Class 'EmployeeSalary' incorrectly implements interface 'EmployeeSalaryInterface'. Property 'name' is private in type 'EmployeeSalary' but not in type 'EmployeeSalaryInterface'.ts(2420)
如果 typescript 不允许在接口(interface)中包含访问修饰符,那么它为什么会提示?
最佳答案
接口(interface)是一个公共(public)协议(protocol)。 “类 A 实现接口(interface) B”的意思是:“类 A 的任何实例发布接口(interface) B 中的所有属性和方法,因此任何使用实例的人都可以使用它们”。
所以,在你的情况下 typescript 行为是正确的
关于javascript - Typescript 提示界面中不存在私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57781371/