![](/img/trans.png)
[英]Typescript how to initialize readonly class member when data is requested asynchronously in constructor
[英]How to initialize readonly member outside constructor for clean code purpose in TypeScript?
我有这样的代码:
class A {
private readonly something: B
constructor() {
this.setup();
// another setup codes ...
}
private setup():void {
this.something = new B();
// another config codes...
}
}
但这将导致错误:
Cannot assign to 'something' because it is a read-only property.
有没有其他解决方案可以在构造函数之外设置只读私有成员?
您可以使用类字段来分配B
属性:
class B { }
class A {
private readonly something = new B()
constructor() {
this.setup();
// another setup codes ...
}
private setup() {
// another config codes...
}
}
不,你不能,这就是 readonly 的目的。 这是只读成员的定义和更多示例的来源
只读成员可以在类外访问,但不能更改其值。 由于只读成员不能在类外更改,它们需要在声明时初始化或在类构造函数内初始化。
readonly
属性只能初始化一次,并且必须始终在构造函数上。
您可以在此处查看有关此事的官方文档。
您可能想要删除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.