简体   繁体   English

从方法而不是构造函数设置只读字段 - 打字稿

[英]set readonly field from method not the constructor - typescript

I have this class我有这堂课

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

}

as you can see I would like to set the fields using setupServices method which will be called from the contractor only .你可以看到,我想通过设置字段setupServices方法,它将从承包商被调用。 of course, this will fail to compile but I'm wondering if there is a way to get around this.当然,这将无法编译,但我想知道是否有办法解决这个问题。

the reason I want this to clean up the contractor.我想让这个清理承包商的原因。

I could do this我可以这样做

constructor() {
    this.serviceA = new AService(...);
    this.serviceB = new BService(...);
    ...
}

but this will make a mass when I have many services但是当我有很多服务时,这会变得很重要

You can use class fields instead:您可以改用类字段:

class Foo { 
    private readonly service1 = new Service1();
    private readonly service2 = new Service2();
    private readonly service3 = new Service3();
}

As a bonus, this also removes the need for explicit type annotations.作为奖励,这也消除了对显式类型注释的需要。

but this will make a mass when I have many services但是当我有很多服务时,这会变得很重要

If you have a large number, consider using an array instead, which will probably be a bit nicer to work with than a whole lot of individual property names.如果您的数字很大,请考虑使用数组代替,这可能比使用大量单个属性名称更好。 Without class fields, this could look something like:如果没有类字段,这可能类似于:

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.

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