Skip to content

Optional

reference
1 min readUpdated

Kind: Function

Source: packages/common/decorators/core/optional.decorator.ts

Part of: Common

Parameter decorator for an injected dependency marking the dependency as optional.

For example:

typescript
constructor(@Optional()

`Optional()` is a parameter decorator that marks a constructor dependency as optional in Nest's dependency injection system. If the requested provider is not available, Nest injects `undefined` instead of throwing a resolution error, allowing the consuming class to handle the absence of that dependency.

## Signature

```ts
function Optional(): PropertyDecorator & ParameterDecorator

Returns: PropertyDecorator & ParameterDecorator

Diagram

mermaid
graph LR
  A[Constructor parameter] --> B["@Optional()"]
  B --> C[Nest dependency injector]
  C -->|Provider available| D[Inject provider instance]
  C -->|Provider unavailable| E[Inject undefined]
  D --> F[Consumer handles dependency]
  E --> F

Usage

typescript
import { Inject, Injectable, Optional } from '@nestjs/common';

@Injectable()
export class AuditService {
  constructor(
    @Optional()
    @Inject('AUDIT_LOGGER')
    private readonly logger?: { log(message: string): void },
  ) {}

  recordEvent(event: string) {
    this.logger?.log(`Audit event: ${event}`);
  }
}

AI Coding Instructions

  • Use @Optional() only on constructor parameters managed by Nest's dependency injection container.
  • Combine it with @Inject() when injecting optional custom tokens, interfaces, or string/symbol-based providers.
  • Type optional dependencies as optional (dependency?: Type) or explicitly handle undefined before using them.
  • Do not use @Optional() to hide required configuration or provider-registration mistakes; use it only when the dependency is genuinely optional.
  • Ensure consumers safely degrade when the provider is absent, for example with optional chaining or a fallback implementation.

Used by

8 references from 8 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (8)

  • DefaultsServiceintegration/injector/src/defaults/defaults.service.ts:4
  • DefaultsServiceintegration/inspector/src/defaults/defaults.service.ts:4
  • AnyFilesInterceptorpackages/platform-express/multer/interceptors/any-files.interceptor.ts:24
  • FileFieldsInterceptorpackages/platform-express/multer/interceptors/file-fields.interceptor.ts:27
  • FileInterceptorpackages/platform-express/multer/interceptors/file.interceptor.ts:25
  • FilesInterceptorpackages/platform-express/multer/interceptors/files.interceptor.ts:27
  • NoFilesInterceptorpackages/platform-express/multer/interceptors/no-files.interceptor.ts:24
  • BaseExceptionFilterpackages/core/exceptions/base-exception-filter.ts:17

Was this page helpful?

Download as PDF
Optional — NestJS head-to-head