属性是私有的,只能在 TS 类中访问

属性是私有的,只能在 TS 类中访问

Property is private and only accessible within class in TS

当我们尝试访问类外的属性时,会出现“属性是私有的,只能在类内访问”的错误private

要解决该错误,请将类属性声明为public需要从类外部访问它。

下面是错误如何发生的示例。

索引.ts
class Employee { // 👇️ private if you need to access only from inside this class private salary: number = 100; logSalary() { console.log(this.salary); } } const employee = new Employee(); // ⛔️ Error: Property 'salary' is private and // only accessible within class 'Employee'.ts(2341) employee.salary; console.log(employee.logSalary()); // 👉️ 100

salary属性具有
私有
成员可见性,因此只能从
Employee类内部访问。

将类属性声明为public

要解决该错误,请为属性分配public可见性。

索引.ts
class Employee { // 👇️ public if you need to access from outside the class public salary: number = 100; } const employee = new Employee(); console.log(employee.salary); // 👉️ 100

默认情况下,类属性具有
公共
可见性。
可以从任何地方访问公共成员。

声明构造函数的参数时可以使用相同的方法。

索引.ts
class Employee { // 👇️ public if you need to access from outside the class constructor(public salary: number) { this.salary = salary; } } const employee = new Employee(200); console.log(employee.salary); // 👉️ 200

私有属性只能在类内部访问

如果将类属性设置为private在构造函数中可见,则只能从类内部访问它。

索引.ts
class Employee { // 👇️ should be public if you need to access // from outside the class constructor(private salary: number) { this.salary = salary; } } const employee = new Employee(200); // ⛔️ Error: Property 'salary' is private and only accessible within class 'Employee'.ts(2341) console.log(employee.salary);

使用受保护的属性时出现错误

使用具有
受保护
可见性的类属性时,您也可能会遇到此错误。

索引.ts
class Employee { // 👇️ protected constructor(protected salary: number) { this.salary = salary; } } const employee = new Employee(200); // ⛔️ Property 'salary' is protected and only accessible // within class 'Employee' and its subclasses.ts(2445) console.log(employee.salary);

受保护的属性只能从类及其子类中访问。

额外资源

您可以通过查看以下教程来了解有关相关主题的更多信息: