The @Optional() decorator marks a constructor dependency as optional. If the provider is not registered in the DI container, NestJS injects undefined instead of throwing an error. Useful when building libraries or optional integrations where a provider may or may not be configured by the consumer.
Building reusable library modules where consumers may not configure all providers.
Feature flags — optionally inject a service only when a feature module is loaded.
Fallback behavior — use a default implementation when the provider is absent.
Always use TypeScript optional typing (?) alongside @Optional() for type safety.
You have a service that sometimes receives a logger via constructor injection, but you want the service to work even if the logger isn’t provided. How would you use @Optional() in the constructor?
If you forget to add @Optional() to a parameter that might be undefined, what runtime error will Nest throw when the provider isn’t registered?
What happens if you mark a parameter with @Optional() but also give it a default value in the constructor signature?
We conditionally register a caching provider based on an env variable. After removing the provider, a controller that injects it started throwing errors. Walk me through how @Optional() could prevent the crash and what changes you’d make in the controller.
During debugging you notice a service injected with @Optional() is always undefined even though the provider is registered in another module. What could cause this and how would you fix it?
Explain the trade‑offs of using @Optional() versus manually checking for a provider’s existence in a factory provider.
Design a reusable NestJS library that offers optional integrations (e.g., a metrics collector). How would you structure the module and use @Optional() so consuming apps can opt‑in without breaking if they don’t install the integration?
Many microservices share a core module that optionally injects a feature‑flag service. Discuss potential pitfalls of overusing @Optional() in that shared module and how you’d mitigate performance or maintainability concerns.
If you need to lazily load an optional provider only when a certain request header is present, how would you combine @Optional() with dynamic module loading to keep the DI container efficient?
Your organization is migrating a monolith to microservices. Several services currently rely on @Optional() to guard against missing legacy providers. What architectural guidelines would you set to decide when @Optional() is appropriate versus refactoring to explicit contracts, and how would you manage the risk of silent failures across teams?
In a large codebase you discover widespread use of @Optional() leading to hidden null‑pointer bugs. Propose a strategy for auditing and refactoring these usages, including tooling, code‑review policies, and documentation updates.