Recall & Review
beginner
What is an optional provider in NestJS?
An optional provider is a service or dependency that a component can use if available, but it won't cause an error if it's missing. NestJS allows marking providers as optional to make dependencies flexible.
Click to reveal answer
beginner
How do you mark a provider as optional in a NestJS constructor?
You use the @Optional() decorator before the dependency in the constructor to tell NestJS that this provider might not be available and it's okay if it's missing.
Click to reveal answer
intermediate
What happens if an optional provider is not found during injection?
If an optional provider is not found, NestJS injects null or undefined instead of throwing an error. This allows the component to handle the missing dependency gracefully.
Click to reveal answer
beginner
Show a simple example of using @Optional() in a NestJS service constructor.
constructor(@Optional() private readonly myService?: MyService) {}
This means myService may be injected if available, or be undefined if not.
Click to reveal answer
intermediate
Why use optional providers in NestJS?
Optional providers help make your code more flexible and reusable. They allow components to work even if some services are not provided, which is useful for features that are not always needed.
Click to reveal answer
Which decorator marks a provider as optional in NestJS?
✗ Incorrect
The @Optional() decorator tells NestJS that the provider may or may not be available.
What does NestJS inject if an optional provider is missing?
✗ Incorrect
NestJS injects null or undefined when an optional provider is missing, allowing graceful handling.
Why would you use optional providers?
✗ Incorrect
Optional providers allow components to work even if some dependencies are missing.
How do you declare an optional provider in a constructor?
✗ Incorrect
Using @Optional() and making the parameter optional with ? marks it as optional.
If you forget to mark a missing provider as optional, what happens?
✗ Incorrect
NestJS throws an error if a required provider is missing and not marked optional.
Explain how to use optional providers in NestJS and why they are useful.
Think about how to avoid errors when a service might not be provided.
You got /4 concepts.
Describe what happens internally when NestJS injects an optional provider that is not registered.
Consider how NestJS handles missing dependencies marked with @Optional().
You got /4 concepts.