typescript - 从构造函数调用的方法中为“只读”属性赋值
问题描述
我有一个简单的类,我想在构造函数启动的方法中为只读属性赋值,但它说[ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property.
为什么我不能为属性赋值,即使我process
从构造函数调用?
示例代码:
class C {
readonly readOnlyProperty: string;
constructor(raw: string) {
this.process(raw);
}
process(raw: string) {
this.readOnlyProperty = raw; // [ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property.
}
}
解决方案
我通常使用这种解决方法。
private _myValue = true
get myValue (): boolean { return this._myValue }
现在您可以从类内部更改属性,并且该属性从外部是只读的。此解决方法的一个优点是您可以重构属性名称而不会产生错误。这就是为什么我不会使用这样的东西(this as any).readOnlyProperty = raw
。
推荐阅读
- qt - QML 无法锚定到布局中的项目
- java - Android 通知通道说明
- excel - 与行和列中的数据匹配的查找公式
- django - 为什么我不能向数据库提交双重表格
- python - 如何确保只有一个进程在 python 多进程中运行一个函数?
- java - 我如何使用电报库进行身份验证并将消息发送到我在 java 中的电话号码?
- python - 为什么在 docker-compose 中使用 python 的 ConnectionError?
- google-cloud-firestore - Firestore 规则 - 限制数据大小
- c# - 删除自引用类的对象时出现 DbUpdateException
- r - 如何在闪亮的反应值中使用去抖动