After upgrading to NestJS 12, why does a subclass provider that redeclares its constructor fail with UnknownDependenciesException where its parent's @Optional() used to apply?
answer
- metadata read on the owner only
- own metadata, not inherited
- redeclared constructor, fresh markers
- silent undefined became an error
basics
~20 sNestJS 12 reads @Optional() markers from the class that declares the constructor, not up the prototype chain. A subclass that redeclares its constructor without its own @Optional() makes the missing token a hard error instead of undefined.
solid answer
~40 s`@Optional()` tells Nest to inject `undefined` when nothing provides a token. Nest 12 reads those markers with `Reflect.getOwnMetadata` on the class that owns the constructor, so a subclass that **redeclares** its constructor no longer inherits the parent's markers. If that subclass injects an unprovided token without its own `@Optional()`, bootstrap throws `UnknownDependenciesException`, where Nest 11 quietly passed `undefined`. The change is deliberate: a genuinely missing dependency used to hide. The fix is to put `@Optional()` back on the subclass's own constructor parameter. In the 12.1.2 injector, a subclass with no constructor of its own still uses its parent's constructor together with its markers.
code
typescript · 27 linesimport { Inject, Injectable, Optional } from '@nestjs/common';
export const RETRY_OPTIONS = Symbol('RETRY_OPTIONS');
export interface RetryOptions {
attempts: number;
}
@Injectable()
export class BaseClient {
constructor(@Optional() @Inject(RETRY_OPTIONS) protected readonly retry?: RetryOptions) {}
}
// Nest 12: UnknownDependenciesException at bootstrap if nothing provides RETRY_OPTIONS
@Injectable()
export class PaymentsClient extends BaseClient {
constructor(@Inject(RETRY_OPTIONS) retry?: RetryOptions) {
super(retry);
}
}
// Fix: declare the marker again on the subclass's own constructor
@Injectable()
export class RefundsClient extends BaseClient {
constructor(@Optional() @Inject(RETRY_OPTIONS) retry?: RetryOptions) {
super(retry);
}
}go deeper
Recall that @Optional() changes only the missing-provider case: Nest injects undefined there instead of failing bootstrap, and the class supplies its own defaults.
Explain own versus inherited reflection metadata and why a redeclared subclass constructor needs its own @Optional() in Nest 12.
Diagnose the post-upgrade UnknownDependenciesException, separate truly optional dependencies from providers v11 silently lost, and pin both with tests.
Use the upgrade to audit shared base classes so optional contracts are explicit on every constructor that relies on them.
## What @Optional() does By default, a NestJS provider whose dependency cannot be resolved stops bootstrap with `UnknownDependenciesException`. Marking the parameter with `@Optional()`, from `@nestjs/common`, changes only that case: if nothing is registered under the token, Nest injects `undefined`, and the class is expected to fall back to defaults. It has no effect when the provider exists. ```typescript @Injectable() export class BaseClient { constructor(@Optional() @Inject(RETRY_OPTIONS) protected readonly retry?: RetryOptions) {} } ``` ## What changed in version 12 Decorators record their information as **reflection metadata** on the class. Metadata lookups come in two flavours: - `Reflect.getMetadata` walks the **prototype chain**, so a subclass sees what its parent recorded. - `Reflect.getOwnMetadata` reads **only the class itself**. The NestJS 12 upgrade guide records the switch: Nest now reads the optional markers of constructor parameters with `Reflect.getOwnMetadata`, so a subclass no longer inherits the markers its parent declared, while parameter types are still inherited. In Nest 11 the parent's markers leaked into the subclass, and a missing provider resolved to `undefined`. The guide calls the change deliberate: a dependency that was genuinely missing used to resolve to `undefined` without any warning. ## Which subclasses are affected In the 12.1.2 source, the injector first finds the **constructor owner**, the nearest class in the prototype chain that carries its own constructor metadata, then reads the optional markers from that class only. The injector's own tests pin the two cases: | Subclass shape | Parameters used | `@Optional()` markers used | |---|---|---| | no constructor of its own | the parent's | the parent's, inherited with the constructor | | redeclares the constructor | its own | only those on its own parameters | So the upgrade bites a subclass that **redeclares** its constructor, typically to call `super(...)` with extra logic, and relied on the parent's `@Optional()`. The upgrade guide's wording also mentions subclasses without a constructor; the 12.1.2 injector and its tests keep the parent's markers in that case, so audit the redeclared constructors first. ## Diagnosing and fixing it The symptom is an app that booted on 11 and now stops with a message such as `Nest can't resolve dependencies of the PaymentsClient (?)`, naming the token at that index. To fix it: 1. Find subclasses of providers whose base constructor uses `@Optional()`. 2. For each one that declares its own constructor, re-apply `@Optional()` (and `@Inject(TOKEN)` for a non-class token) on the matching parameter. 3. Decide, case by case, whether the dependency really is optional. The new error may be exposing a provider that was never registered by mistake; then register it instead of marking it optional. 4. Add a test module that boots the subclass without the optional provider, so the behaviour is pinned. ## Reading the failure On version 12 the message has the usual shape: Nest names the class it was building, replaces the unresolved position with `?`, and names the token at that index. Two details tell this case apart from an ordinary missing export: - The same class booted on version 11 with no code change except the upgrade. - The unresolved token is one the base class marks `@Optional()`, and the failing class is a subclass that declares its own constructor. If either detail is missing, look for an ordinary cause instead: a provider not exported, a module not imported, or an `import type` that erased a class. ## Why it matters beyond the upgrade - Optional dependencies are a contract: the class promises to work without them. Making each constructor state that contract itself keeps it visible where the parameters are declared. - A silent `undefined` usually fails far from its cause, at the first method call; an error at bootstrap points at the exact class and token. - Base classes shipped by shared libraries are where this surfaces most, because their consumers subclass them across many services.
- Does a subclass with no constructor of its own lose the parent's @Optional() in NestJS 12.1.2?No. The 12.1.2 injector resolves such a subclass through the parent's constructor and reads the optional markers from that constructor's owner, so the parent's markers still apply. Only a subclass that redeclares its constructor uses its own markers alone; the upgrade guide's broader wording is worth checking against your version.
- Should every failing parameter simply get @Optional() back after the upgrade?Not automatically. The error may reveal a provider that was supposed to be registered and never was, which v11 masked as `undefined`. Restore `@Optional()` only where the class really works without the dependency; otherwise register the provider.
- @Optional() on a base class still covers every subclass constructor in Nest 12.
- @Optional() makes Nest inject undefined even when the provider exists.
- Nest 12 stopped inheriting constructor parameter types as well as optional markers.
- The fix is to register a null value under every optional token.
Assumes NestJS 12 (checked against 12.1.2); 11 read @Optional() markers through the prototype chain, so a redeclared constructor inherited them.