TypeScript 中 A class member cannot have the ‘const’ keyword 错误
当我们使用 const
关键字在类中声明属性时,会出现“A class member cannot have the ‘const’ keyword”的错误。 要解决该错误,请删除 const
关键字并使用 readonly
修饰符来指示不应更改类属性。
下面是发生上述错误的示例
class Employee {
// ⛔️ A class member cannot have the 'const' keyword.ts(1248)
const name = 'James';
}
声明类属性时不能使用 const
关键字。 相反,请使用 readonly
修饰符。
class Employee {
readonly name = 'James';
readonly age = 24;
logName() {
console.log(this.name);
}
}
const emp = new Employee();
emp.logName(); // 👉️ "James"
console.log(emp.name); // 👉️ "James"
我们使用 readonly
修饰符来防止在构造函数之外对类属性进行赋值。
使用这种方法时,我们仍然可以在构造函数中更改属性的值。
class Employee {
readonly name: string = 'James';
readonly age: number = 24;
constructor() {
this.name = 'Freddy';
this.age = 29;
}
logName() {
console.log(this.name);
}
}
const emp = new Employee();
console.log(emp.name); // 👉️ "Freddy"
在构造函数之外赋值会导致类型检查器发出错误。
class Employee {
readonly name: string = 'James';
readonly age: number = 24;
constructor() {
this.name = 'Freddy';
this.age = 29;
}
logName() {
console.log(this.name);
// ⛔️ Cannot assign to 'name' because it
// is a read-only property.ts(2540)
this.name = 'Jiyik';
}
}
如果我们不希望能够更改构造函数中的值,则可以将 static
关键字与 readonly
一起使用。
export class Employee {
// 👇️ public if you need to access from outside the class
public static readonly department = 'Accounting';
// 👇️ private if you need to access only from inside this class
private static readonly salary = 100;
// 👇️ protected if you need to access only from this class
// and its subclasses
protected static readonly age = 30;
logSalary() {
console.log(Employee.salary);
console.log(Employee.age);
}
}
// 👇️ Access on class (NOT on instances)
console.log(Employee.department);
使用
static
关键字时,我们定义了静态方法或属性。 静态方法和属性不能在类的实例上访问,它们只能在类本身上访问。
示例中的 department
属性被声明为 public
。 声明为公共的属性可以在任何地方访问。
当我们需要从类外部访问特定属性时,我们应该使用
public
。
私有可见性只允许从类内部访问。
标记为受保护的成员仅对类本身及其子类可见。
确保我们正在访问类的静态属性和方法,例如 Employee.myProperty
,而不是类的实例。
如果大家不喜欢本文介绍的任何方法,那可以在类外部声明一个常量并在类中使用它。
const name = 'Frank';
export class Employee {
logName() {
console.log(name);
}
}
const employee = new Employee();
employee.logName(); // 👉️ "Frank"
总结
当我们使用 const
关键字在类中声明属性时,会出现“A class member cannot have the ‘const’ keyword”的错误。 要解决该错误,请删除 const
关键字并使用 readonly
修饰符来指示不应更改类属性。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。