【问题标题】:Typescript complains that private property is not present in the interface打字稿抱怨接口中不存在私有属性
【发布时间】:2020-01-06 22:23:20
【问题描述】:

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

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`
    }
}

现在,打字稿不允许我在界面中创建私有属性。但是,由于某种原因,如果我在具有私有属性的类中实现该接口,则会抛出 Class 'EmployeeSalary' incorrectly implements interface 'EmployeeSalaryInterface'. Property 'name' is private in type 'EmployeeSalary' but not in type 'EmployeeSalaryInterface'.ts(2420)

如果 typescript 不允许在接口中包含访问修饰符,那它为什么会抱怨呢?

【问题讨论】:

  • 它抱怨是因为你的类型没有实现接口。
  • 为什么要在接口中定义私有属性?它不是公共 API 的一部分。
  • @zerkms 你这是什么意思?
  • @Sanjay 你的类型没有实现接口 -> 你没有得到类型检查异常。目前尚不清楚您的问题到底是什么。你在接口中声明了name: string字段,你的类没有实现它。

标签: javascript typescript class interface


【解决方案1】:

接口是公共协议。声明“A 类实现接口 B”的意思是:“A 类的任何实例发布来自接口 B 的所有属性和方法,因此任何使用实例的人都可以使用它们”。

所以,在你的情况下打字稿行为是正确的

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 2016-09-21
    • 2018-10-14
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多