javascript - Typescript 提示界面中不存在私有(private)属性

标签 javascript typescript class interface

我有以下非常基本的代码:

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)

enter image description here

如果 typescript 不允许在接口(interface)中包含访问修饰符,那么它为什么会提示?

最佳答案

接口(interface)是一个公共(public)协议(protocol)。 “类 A 实现接口(interface) B”的意思是:“类 A 的任何实例发布接口(interface) B 中的所有属性和方法,因此任何使用实例的人都可以使用它们”。

所以,在你的情况下 typescript 行为是正确的

关于javascript - Typescript 提示界面中不存在私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57781371/

相关文章:

C++ 两个类在构造函数中需要彼此?

javascript - 如何使加载动画 gif 在 getjson 调用完成后不可见并显示 jw 播放器?

javascript - 如何在 Ext.net 中使用 JavaScript 获取 UserControl 中控件的元素 ID

javascript - 是否可以在不使用外部后端的情况下编写 grafana 数据源插件?

javascript - 使用 Angular 和 Rxjs 处理多个 HTTP 请求并返回结果

php - 如何在 PHP 中构造类

javascript - V8:ES6 代理在针对自定义对象时不支持迭代协议(protocol)?

typescript - 为什么不将类型参数推断为联合类型?

JavaScript/TypeScript Array interface[] ,按类型分组以发送多个函数中的 1 个

.net - 私有(private)嵌套类