Bird
Raised Fist0
NestJSframework~20 mins

Optional providers in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Optional Provider Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an optional provider is not registered?
In NestJS, if a service is injected as an optional provider but is not registered in the module, what will be the value of the injected dependency inside the consuming class?
NestJS
import { Injectable, Optional } from '@nestjs/common';

@Injectable()
export class ConsumerService {
  constructor(@Optional() private readonly optionalService?: OptionalService) {}

  getStatus() {
    return this.optionalService ? 'Service available' : 'Service missing';
  }
}

// Assume OptionalService is NOT provided in any module
AThe constructor will not be called because of missing provider
B'Service available' because NestJS creates a default instance automatically
CThrows a runtime error due to missing provider
D'Service missing' because the optional provider is undefined when not registered
Attempts:
2 left
💡 Hint
Think about what @Optional() decorator does when the provider is missing.
📝 Syntax
intermediate
2:00remaining
Identify the correct syntax to mark a provider as optional in NestJS
Which of the following constructor parameter declarations correctly marks a provider as optional in NestJS?
NestJS
import { Injectable, Optional } from '@nestjs/common';

@Injectable()
export class ExampleService {
  constructor( /* ??? */ ) {}
}
Aconstructor(@Optional() private readonly service: SomeService) {}
Bconstructor(private readonly service: @Optional() SomeService) {}
Cconstructor(private readonly @Optional() service: SomeService) {}
Dconstructor(private readonly service?: SomeService) {}
Attempts:
2 left
💡 Hint
Look at how decorators are placed before parameters in TypeScript.
❓ state_output
advanced
2:00remaining
What is the output when an optional provider is injected and used?
Given the following NestJS service and module setup, what will be the output of the method call consumer.getMessage()?
NestJS
import { Injectable, Optional } from '@nestjs/common';

@Injectable()
export class OptionalService {
  getMessage() {
    return 'Hello from OptionalService';
  }
}

@Injectable()
export class ConsumerService {
  constructor(@Optional() private readonly optionalService?: OptionalService) {}

  getMessage() {
    return this.optionalService?.getMessage() ?? 'No service available';
  }
}

// Module setup:
// @Module({
//   providers: [ConsumerService] // OptionalService is NOT provided
// })
A'Hello from OptionalService'
BThrows a runtime error because optionalService is undefined
C'No service available'
DReturns undefined
Attempts:
2 left
💡 Hint
Check how the optionalService is used with optional chaining and fallback.
🔧 Debug
advanced
2:00remaining
Why does this optional provider injection cause a runtime error?
Consider this NestJS service constructor:
constructor(@Optional() private readonly service: SomeService) {}
If SomeService is not provided in any module, why might this code still cause a runtime error?
NestJS
import { Injectable, Optional } from '@nestjs/common';

@Injectable()
export class ConsumerService {
  constructor(@Optional() private readonly service: SomeService) {
    console.log(this.service.getName());
  }
}
ABecause service is undefined and calling getName() on undefined causes a runtime error
BBecause @Optional() decorator is missing
CBecause NestJS always throws error if provider is missing regardless of @Optional()
DBecause the constructor is missing the @Inject decorator
Attempts:
2 left
💡 Hint
Think about what happens when you call a method on undefined in JavaScript.
🧠 Conceptual
expert
2:00remaining
How does NestJS resolve optional providers during dependency injection?
Which statement best describes how NestJS handles optional providers when resolving dependencies?
ANestJS throws an error if the provider is not registered, even if marked optional
BNestJS injects undefined for optional providers if they are not registered, allowing the consumer to handle absence gracefully
CNestJS injects a default instance of the provider if it is not registered, ensuring no errors occur
DNestJS skips the constructor parameter entirely if the provider is optional and missing
Attempts:
2 left
💡 Hint
Consider what @Optional() means for dependency injection behavior.

Practice

(1/5)
1. What is the main purpose of using @Optional() in a NestJS provider?
easy
A. To make a provider always required and throw error if missing
B. To mark a dependency as optional, so it may be undefined if not provided
C. To automatically create a new instance of the provider
D. To disable dependency injection for that provider

Solution

  1. Step 1: Understand the role of @Optional()

    @Optional() tells NestJS that the dependency might not be available and should not cause an error if missing.
  2. Step 2: Compare with required providers

    Without @Optional(), NestJS throws an error if the provider is not found. With @Optional(), it injects undefined instead.
  3. Final Answer:

    To mark a dependency as optional, so it may be undefined if not provided -> Option B
  4. Quick Check:

    @Optional() = marks provider optional [OK]
Hint: Optional means provider can be missing without error [OK]
Common Mistakes:
  • Thinking @Optional() makes provider required
  • Assuming @Optional() creates new instances
  • Believing @Optional() disables injection
2. Which of the following is the correct way to inject an optional provider in a NestJS constructor?
easy
A. constructor(@Optional() private readonly service: MyService) {}
B. constructor(private readonly service: MyService) {}
C. constructor(@InjectOptional() private readonly service: MyService) {}
D. constructor(@Optional private service: MyService) {}

Solution

  1. Step 1: Recall the correct decorator syntax

    The correct decorator to mark a provider optional is @Optional() with parentheses.
  2. Step 2: Check each option

    constructor(private readonly service: MyService) {} lacks @Optional, so provider is required. constructor(@InjectOptional() private readonly service: MyService) {} uses a non-existent decorator. constructor(@Optional private service: MyService) {} misses parentheses on @Optional.
  3. Final Answer:

    constructor(@Optional() private readonly service: MyService) {} -> Option A
  4. Quick Check:

    @Optional() decorator syntax requires parentheses [OK]
Hint: Use @Optional() with parentheses before the parameter [OK]
Common Mistakes:
  • Forgetting parentheses on @Optional()
  • Using wrong decorator names
  • Not marking provider optional in constructor
3. Given the following code, what will be the output when MyService is NOT provided in the module?
constructor(@Optional() private readonly myService?: MyService) {}

useService() {
  return this.myService ? 'Service available' : 'Service missing';
}
medium
A. "Service missing"
B. "Service available"
C. Runtime error: Cannot read property of undefined
D. Compilation error due to missing provider

Solution

  1. Step 1: Understand @Optional() effect when provider missing

    When MyService is not provided, the injected value is undefined, not an error.
  2. Step 2: Analyze the useService method

    The method checks if myService exists. Since it's undefined, it returns "Service missing".
  3. Final Answer:

    "Service missing" -> Option A
  4. Quick Check:

    Missing optional provider = undefined, so returns "Service missing" [OK]
Hint: Optional provider missing means undefined, check before use [OK]
Common Mistakes:
  • Expecting runtime error when provider missing
  • Assuming provider is always injected
  • Ignoring undefined check before usage
4. Identify the error in this NestJS service constructor using an optional provider:
constructor(@Optional() private readonly service: MyService) {
  this.service.doSomething();
}
medium
A. Missing @Inject decorator for MyService
B. Service should not be private readonly
C. Calling method on possibly undefined service without check
D. Incorrect use of @Optional() decorator without parentheses

Solution

  1. Step 1: Check usage of optional provider

    @Optional() means service can be undefined if not provided.
  2. Step 2: Analyze method call in constructor

    Calling this.service.doSomething() without checking if service exists can cause runtime error.
  3. Final Answer:

    Calling method on possibly undefined service without check -> Option C
  4. Quick Check:

    Always check optional provider before use [OK]
Hint: Check if optional provider exists before calling methods [OK]
Common Mistakes:
  • Calling methods on undefined optional providers
  • Assuming @Optional() means always injected
  • Ignoring runtime errors from missing checks
5. You want to inject an optional logging service in your NestJS component. If the logging service is missing, your component should still work without errors. Which approach correctly implements this behavior?
export class MyComponent {
  constructor(@Optional() private readonly logger?: LoggerService) {}

  logMessage(msg: string) {
    // What should you do here?
  }
}
hard
A. Call this.logger.log(msg) directly without checks
B. Throw an error if this.logger is undefined
C. Remove @Optional() to ensure logger is always injected
D. Use if (this.logger) this.logger.log(msg); to check before calling

Solution

  1. Step 1: Understand optional injection with @Optional()

    The logger may be undefined if not provided, so direct calls risk runtime errors.
  2. Step 2: Implement safe usage in method

    Check if this.logger exists before calling log() to avoid errors.
  3. Final Answer:

    Use if (this.logger) this.logger.log(msg); to check before calling -> Option D
  4. Quick Check:

    Check optional provider exists before use to avoid errors [OK]
Hint: Always check optional provider before method calls [OK]
Common Mistakes:
  • Calling methods without existence check
  • Throwing errors instead of handling missing provider
  • Removing @Optional() and causing injection errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard