Performance: Optional providers
This affects the application startup time and memory usage by controlling whether certain services are instantiated or skipped.
constructor(@Optional() private readonly optionalService?: OptionalService) {}constructor(private readonly optionalService: OptionalService) {}| Pattern | Service Instantiation | Startup Delay | Memory Usage | Verdict |
|---|---|---|---|---|
| Mandatory provider injection | Always instantiated | Increases delay | Higher memory use | [X] Bad |
| Optional provider injection | Instantiated only if provided | Minimal delay | Lower memory use | [OK] Good |
@Optional() in a NestJS provider?@Optional() with parentheses.MyService is NOT provided in the module?
constructor(@Optional() private readonly myService?: MyService) {}
useService() {
return this.myService ? 'Service available' : 'Service missing';
}myService exists. Since it's undefined, it returns "Service missing".constructor(@Optional() private readonly service: MyService) {
this.service.doSomething();
}this.service.doSomething() without checking if service exists can cause runtime error.export class MyComponent {
constructor(@Optional() private readonly logger?: LoggerService) {}
logMessage(msg: string) {
// What should you do here?
}
}this.logger exists before calling log() to avoid errors.Pass the test and this pattern moves unknown