Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to `readonly` properties from methods called by the constructor

I have a simple class, and I want to assign a value to a readonly property in a method initiated by the constructor, but it says [ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property. Why can't I assign a value to the property even though I am calling process from the constructor?

Sample Code:

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.
    }
}
like image 491
Bill Avatar asked Sep 21 '18 05:09

Bill


Video Answer


2 Answers

I usually use this workaround.

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

Now you can change the property from within the class and the property is readonly from the outside. One advantage of this workaround is that you can refactor your property names without generating errors. That's why I wouldn't use something like this (this as any).readOnlyProperty = raw.

like image 149
Jan Avatar answered Oct 29 '22 16:10

Jan


Instead of "casting" this as any, you can still enforce type checking by modifying just this property:

(this.readOnlyProperty as string) = raw; // OK
(this.readOnlyProperty as string) = 5;   // TS2322: Type '5' is not assignable to type 'string'.

like image 32
Michael Chen Avatar answered Oct 29 '22 16:10

Michael Chen