microsoft / tsyringe

Lightweight dependency injection container for JavaScript/TypeScript
MIT License
5.18k stars 172 forks source link

inject optional parameters #207

Open Harshita-mindfire opened 2 years ago

Harshita-mindfire commented 2 years ago

Extremely new to the DI tsyringe, how do we handle optional parameters with@inject decorator? With the below setup, I get the following error:

Cannot inject the dependency siteUtils in UtilsWeb, Reason: TypeInfo not known for "undefined"

My use case is : the siteUrl and enablePrettyLinks can have undefined values. They are being read from a .yml file

-------------
  container.register("siteUrl", { useValue: siteUrl }); // siteUrl can have undefined value
  container.register("enablePrettyLinks", { useValue: enablePrettyLinks }); // enablePrettyLinks can have undefined value
------------------

@injectable()
export class UtilsWeb {
  constructor(
    @inject("siteUrl") private siteUrl?: string,
    @inject("enablePrettyLinks") private enablePrettyLinks?: boolean
  ) {}
...
}