function Optional
Since 0.2.0
Optional(token: string): OptionalToken

Marks a constructor dependency as optional: when the token has no provider, the argument receives undefined instead of failing construction.

Used inside Inject, in the position of the argument it describes.

Optional means the dependency is absent, not that construction may fail: a token that IS provided is resolved normally, and an error thrown while building it — a circular dependency, a throwing factory — propagates rather than being swallowed into undefined.

Honored identically on both construction paths: the DI container when one is registered, and the kernel's service registry otherwise.

Examples

Example 1

@Injectable()
@Inject(CAPABILITIES.DATABASE, Optional(CAPABILITIES.CACHE))
class ReportService {
  constructor(private db: Db, private cache?: ICacheService) {}
}

Parameters

token: string

The capability token to resolve when a provider exists

Return Type

An optional-token marker for use inside @Inject

Usage

import { Optional } from "decorator-plugin/src/index.ts";