1

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. 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

1
  • Using a class decorator may be an alternative. I don't know if it is a more elegant solution but it might keep your class neater. Commented Oct 30, 2020 at 18:24

1 Answer 1

1

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
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for answering, your suggestion is very good. in the case of using the array, I think that will not be useful since the services of different type, and I also should have const index values for every service that I would like to use

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.