@Optional()
Marks an injected dependency as optional so resolution does not fail when absent.
Syntax
@Optional() Returns
ParameterDecorator — A decorator applied to a constructor parameter.
Examples
import { Injectable, Optional, Inject } from '@nestjs/common';
@Injectable()
export class HttpService {
constructor(
@Optional() @Inject('HTTP_OPTIONS') private options?: { timeout: number },
) {
this.options ??= { timeout: 5000 };
}
}
Notes
Without @Optional(), Nest throws if a dependency cannot be resolved. With
it, the parameter receives undefined so you can supply sensible defaults.