首页 > 解决方案 > 从构造函数调用的方法中为“只读”属性赋值

问题描述

我有一个简单的类,我想在构造函数启动的方法中为只读属性赋值,但它说[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.
    }
}

标签: typescriptclassconstructorreadonly-attribute

解决方案


我通常使用这种解决方法。

  private _myValue = true
  get myValue (): boolean { return this._myValue }

现在您可以从类内部更改属性,并且该属性从外部是只读的。此解决方法的一个优点是您可以重构属性名称而不会产生错误。这就是为什么我不会使用这样的东西(this as any).readOnlyProperty = raw


推荐阅读