[英]Typescript: assign a readonly attribute in a function inside the constructor
[英]set readonly field from method not the constructor - typescript
我有这堂课
class Foo {
private readonly serviceA : AService;
private readonly serviceB : BService;
private readonly serviceC : CService;
...
constructor() {
this.setupService();
...
}
private setupService() : void {
this.serviceA = new ServiceA(...);
this.serviceB = new ServiceB(...);
...
}
}
你可以看到,我想通过设置字段setupServices
方法,它将只从承包商被调用。 当然,这将无法编译,但我想知道是否有办法解决这个问题。
我想让这个清理承包商的原因。
我可以这样做
constructor() {
this.serviceA = new AService(...);
this.serviceB = new BService(...);
...
}
但是当我有很多服务时,这会变得很重要
您可以改用类字段:
class Foo {
private readonly service1 = new Service1();
private readonly service2 = new Service2();
private readonly service3 = new Service3();
}
作为奖励,这也消除了对显式类型注释的需要。
但是当我有很多服务时,这会变得很重要
如果您的数字很大,请考虑使用数组代替,这可能比使用大量单个属性名称更好。 如果没有类字段,这可能类似于:
class Foo {
// type could be made more precise via tuple if needed
private readonly services: ServiceObj[];
constructor() {
this.services = this.makeServices();
}
makeServices() {
// create and return array of services
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.