简体   繁体   English

如何在 TypeScript 中为了干净的代码目的在构造函数外初始化只读成员?

[英]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:您可以使用类字段来分配B属性:

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.不,你不能,这就是 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. readonly属性只能初始化一次,并且必须始终在构造函数上。

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:您可能想要删除readonly并添加一个setter ,这样,您只需使用 set 函数来更改属性值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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