young-steveo / bottlejs

A powerful dependency injection micro container for JavaScript applications
MIT License
1.29k stars 67 forks source link

feat(types): support limiting/type checking entry names #115

Closed ethanresnick closed 6 years ago

ethanresnick commented 6 years ago

The idea behind this PR is that it's often useful when working in Typescript to be able to say that your service names will come from some pre-defined list, to (e.g.) prevent typos when declaring dependencies, or to get the compiler to error if you remove a service that another service still depends on. This PR makes that possible.

Usage:

  type LegalName = 'Service1' | 'Service2';

  const bottle = new Bottle<LegalName>();
  bottle.constant('Service1', 3); // Ok
  bottle.constant('Service3', 3); // Errors, no Service3
  bottle.service('Service1', class {}, 'Service2');
  bottle.service('Service2',  class {}, 'Service3'); // errors, no Service3.

Note that the type parameter for Bottle (LegalName in the example) will default to string if not provided, so this won't break any existing uses or require extra boilerplate for users who don't care about this safety.

young-steveo commented 6 years ago

Awesome, thanks for the contrib!

young-steveo commented 6 years ago

I'll release it on the next version.