0
0
NestJSframework~10 mins

Optional providers in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to mark the provider as optional in the constructor.

NestJS
constructor(@[1]() private readonly service?: MyService) {}
Drag options to blanks, or click blank then click option'
AInject()
BController()
CInjectable()
DOptional()
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Injectable() instead of @Optional()
Forgetting to add the decorator
Using @Inject() alone without @Optional()
2fill in blank
medium

Complete the code to import the Optional decorator from the correct package.

NestJS
import { [1] } from '@nestjs/common';
Drag options to blanks, or click blank then click option'
AInjectable
BOptional
CController
DModule
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Injectable instead of Optional
Importing from wrong package
Misspelling the decorator name
3fill in blank
hard

Fix the error in the constructor to correctly inject an optional provider.

NestJS
constructor(@Optional() private readonly service?: [1]) {}
Drag options to blanks, or click blank then click option'
AOptional<MyService>
BMyService?
CMyService
DMyService | null
Attempts:
3 left
💡 Hint
Common Mistakes
Changing the type to a union or optional type instead of using the decorator
Not using @Optional() decorator
Using incorrect syntax for optional types
4fill in blank
hard

Fill both blanks to correctly inject an optional provider with a custom token.

NestJS
constructor(@[1]('MY_TOKEN') @[2]() private readonly service?: MyService) {}
Drag options to blanks, or click blank then click option'
AInject
BOptional
CController
DInjectable
Attempts:
3 left
💡 Hint
Common Mistakes
Reversing the order of decorators
Using wrong decorators like @Controller or @Injectable
Omitting @Optional() decorator
5fill in blank
hard

Fill all three blanks to create an optional provider with a default value fallback.

NestJS
const defaultService = [3];

constructor(@[1]() private readonly service?: MyService) {
  this.service = this.service ?? [2];
}
Drag options to blanks, or click blank then click option'
AOptional
BdefaultService
Cnew MyService()
DInject
Attempts:
3 left
💡 Hint
Common Mistakes
Not using @Optional() decorator
Forgetting to assign default value
Using wrong variable names