NestJS Introduction 2 — Questions and Answers
Question 1: Which TypeScript decorator marks a class as a NestJS module?
- @Injectable()
- @Module() (Correct answer)
- @Controller()
- @Component()
Correct answer: @Module()
@Module() decorator tells NestJS that the class is a module and provides metadata to organize the application structure.
Question 2: What is the purpose of the 'providers' array inside a @Module() decorator?
- Register HTTP routes
- Declare injectable services available via dependency injection (Correct answer)
- Import external modules
- Export controllers
Correct answer: Declare injectable services available via dependency injection
The 'providers' array registers services and other injectables that the NestJS DI system will instantiate and manage.
Question 3: Which command creates a new NestJS project using the Nest CLI?
- nest generate app myapp
- nest new myapp (Correct answer)
- nestjs create myapp
- npm init nestjs myapp
Correct answer: nest new myapp
'nest new myapp' scaffolds a new NestJS project with default configuration, package.json, and boilerplate files.
Question 4: What does the 'imports' array in @Module() accomplish?
- Imports TypeScript files
- Makes exported providers of other modules available (Correct answer)
- Registers middleware
- Declares global guards
Correct answer: Makes exported providers of other modules available
The 'imports' array allows a module to use providers that are exported by other imported modules.
Question 5: NestJS uses which design pattern for its dependency injection system?
- Singleton factory
- Inversion of Control (IoC) container (Correct answer)
- Observer pattern
- Proxy pattern
Correct answer: Inversion of Control (IoC) container
NestJS implements an IoC container where dependencies are declared and resolved automatically rather than being manually instantiated.
Question 6: What is the default scope of a provider in NestJS?
- Transient — new instance per injection
- Request — new instance per HTTP request
- Singleton — one instance per module (Correct answer)
- Global — one instance per application
Correct answer: Singleton — one instance per module
By default, providers in NestJS are singletons within the module, meaning the same instance is shared across all consumers.
Question 7: Which file is the entry point of a NestJS application created by the CLI?
- app.module.ts
- main.ts (Correct answer)
- index.ts
- server.ts
Correct answer: main.ts
main.ts calls NestFactory.create() to bootstrap the application and starts the HTTP listener.
Which TypeScript decorator marks a class as a NestJS module?