Ivan Elianto
Ivan Elianto

Reputation: 442

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 ?

Upvotes: 0

Views: 1665

Answers (3)

rleiva93
rleiva93

Reputation: 246

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());
  } 
}

Upvotes: 0

Edward Romero
Edward Romero

Reputation: 3106

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

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370769

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

Upvotes: 1

Related Questions