Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
How does the private keyword let us both declare and initialize a class instance?

I'm reading the Nest.js documentation, and there is a line that I don't quite understand.

We customize our CatsController using its constructor function, so when the IoC container creates the catsController instance, it is created with a catsService instance as a constructor parameter. At least this is my best guess based on the whole document. But what does the following exactly mean:

Notice the use of the private syntax. This shorthand allows us to both declare and initialize the catsService member immediately in the same location.

Why does the private keyword achieve that? How would it look if we did not use the shorthand syntax?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The initialization of the CatsService is done by Nest.js in both cases, that's one of the key premises of the IoC it relies on. The usage of the private keyword in constructor declaration is completely optional, and is useful for making the constructor parameter an attribute of CatsController during its initialization. Without it, you should write:

@Controller('cats')
export class CatsController {
  private catsService: CatsService;
  
  constructor(service: CatsService) {
    this.catsService = service;
  }
  /* TODO */
}

Look at how the private keyword comes in place to declare the catsService as a private attribute of the class, and if we were to use it inside the constructor parameter declaration it would have the same meaning, resulting in a smaller and simpler code. Lastly, this is a syntactic feature of Typescript, and has no relation with NestJS or DI.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!