在TypeScript中,如何在构造函数外部初始化只读成员以实现干净的代码目的?
我有这样的代码:在TypeScript中,如何在构造函数外部初始化只读成员以实现干净的代码目的?,typescript,Typescript,我有这样的代码: class A { private readonly something: B constructor() { this.setup(); // another setup codes ... } private setup():void { this.something = new B(); // another config codes... } } 但这将导致一个错误: 无法分配给“某物”,因为它是只读属性。
class A {
private readonly something: B
constructor() {
this.setup();
// another setup codes ...
}
private setup():void {
this.something = new B();
// another config codes...
}
}
但这将导致一个错误:无法分配给“某物”,因为它是只读属性。
是否有其他解决方案可以在构造函数外部设置只读私有成员?您可以使用类字段来指定
B
属性:
class B { }
class A {
private readonly something = new B()
constructor() {
this.setup();
// another setup codes ...
}
private setup() {
// another config codes...
}
}
不,你不能,这就是只读的目的。下面是只读成员的定义和源代码,并提供了更多示例 只读成员可以在类外访问,但不能更改其值。由于只读成员不能在类外部更改,因此它们需要在声明时初始化,或者在类构造函数内部初始化
只读属性只能初始化一次,并且必须始终在构造函数上 你可以查阅有关此事的官方文件 您可能希望删除
只读
并添加设置器
,这样,您只需使用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());
}
}
这听起来不像是“干净的代码”。一旦你把它从构造函数/文件初始值设定项中取出-一些东西将不再是只读的(设置可以从任何其他方法调用)。如果您有复杂的init逻辑,可以将其提取到函数中并在构造函数中调用:this.something=this.createSomething()