Skip to content

Commit

Permalink
feat: allow to type available services
Browse files Browse the repository at this point in the history
  • Loading branch information
nikku committed Feb 4, 2024
1 parent 475e6e6 commit 01f9eaf
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/index.d.ts
Expand Up @@ -71,13 +71,21 @@ export type LocalsMap = {

export type ModuleDefinition = ModuleDeclaration;

export class Injector {

export class Injector<
ServiceMap = null
> {

/**
* Create an injector from a set of modules.
*/
constructor(modules: ModuleDefinition[], parent?: InjectorContext);

/**
* Return a named service, looked up from the existing service map.
*/
get<Name extends keyof ServiceMap>(name: Name): ServiceMap[Name];

/**
* Return a named service, and throws if it is not found.
*/
Expand Down
33 changes: 33 additions & 0 deletions test/integration/ts.spec.ts
Expand Up @@ -59,6 +59,39 @@ describe('typed', function() {
expect(injector).to.exist;
});


it('should offer typed injections', function() {

// given
type ServiceMap = {
'foo': 1,
'bar': 'BAR'
};

// when
const injector = new Injector<ServiceMap>([
{
foo: [ 'value', 1 ],
bar: [ 'value', 'BAR' ]
}
]);

// then
const foo = injector.get('foo');
expect(foo).to.eql(1);

const bar = injector.get('bar');
expect(bar).to.eql('BAR');

const baz = injector.get('baz', false);
expect(baz).not.to.exist;

// illegal usage, but if you think you know better
// we still accept it
const boolBar = injector.get<boolean>('bar');
expect(boolBar).to.exist;
});

});


Expand Down

0 comments on commit 01f9eaf

Please sign in to comment.