typescriptclassconstructorreadonly-attribute

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.
    }
}

Solution

  • I usually use this workaround:

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

    Result:

    The advantage of this workaround is that your IDE can refactor your property. Also, we do not misuse a non-writable readonly property, which can lead to errors when compiling, optimizing, or code review. If not today, then in the near future. That's why I wouldn't use something like:

    // hack, may cause problems (refactoring is not possible)
    (this as any).readOnlyProperty = raw
    
    // hack, may cause problems (we write a non-writable)
    (this.readOnlyProperty as boolean) = raw
    
    // hack, may cause problems (refactoring is not possible)
    Object.assign(this, {readOnlyProperty: raw})