简体   繁体   中英

How to initialize readonly member outside constructor for clean code purpose in TypeScript?

I have code like this:

class A {
  private readonly something: B

  constructor() {
    this.setup();
    // another setup codes ...  
  }

  private setup():void {
    this.something = new B();
    // another config codes...
  }
}

But this will be result an error:
Cannot assign to 'something' because it is a read-only property.

Is there any alternative solution to setup readonly private members outside constructor ?

You can assign the B property with a class field instead:

class B { }
class A {
  private readonly something = new B()

  constructor() {
    this.setup();
    // another setup codes ...  
  }

  private setup() {
    // another config codes...
  }
}

No you can't, that's the purpose of readonly. Here is the definition of readonly members and the source with more examples

Read-only members can be accessed outside the class, but their value cannot be changed. Since read-only members cannot be changed outside the class, they either need to be initialized at declaration or initialized inside the class constructor.

Source

The readonly properties must be initialized only once, and it must be always on the constructor.

You can check the official documentation regarding that matter here .

You might want to remove the readonly and add a setter , in that way, you only use the set function to change the property value:

class A {
  private _something: B;

  constructor() {
    this.setup();
    // another setup codes ...  
  }

  set something(value: B) {
        this._something = value;
  }

  private setup():void {
    // This setup a new value and makes sure that not other piece of code 
    // changes it. Only through the setter will work
    this.something(new B());
  } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM