Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 023ac7f

Browse files
committedNov 28, 2024
Fix constructor return type inference for published npm.
1 parent 3b333d1 commit 023ac7f

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed
 

‎src/Container.ts

+21-4
Original file line numberDiff line numberDiff line change
@@ -417,19 +417,36 @@ export class Container<Services = {}> {
417417
* specifying these dependencies.
418418
* @returns A new Container instance containing the newly created service, allowing for method chaining.
419419
*/
420-
providesClass = <
420+
providesClass<
421421
Token extends TokenType,
422422
Tokens extends readonly ValidTokens<Services>[],
423423
Class extends {
424424
readonly dependencies: Tokens;
425-
new (...args: Params): InstanceType<Class>;
425+
new (...args: Params): any;
426426
},
427427
Params extends MapTokensToTypes<Services, Class["dependencies"]>,
428428
>(
429429
token: Token,
430430
cls: Class
431-
): Container<AddService<Services, Token, InstanceType<Class>>> =>
432-
this.providesService(Injectable(token, cls.dependencies, (...args: Params) => new cls(...args)));
431+
): Class extends {
432+
readonly dependencies: Tokens;
433+
new (...args: Params): infer Service;
434+
}
435+
? Container<AddService<Services, Token, Service>>
436+
: never;
437+
438+
providesClass<
439+
Service,
440+
Token extends TokenType,
441+
Tokens extends readonly ValidTokens<Services>[],
442+
Class extends {
443+
readonly dependencies: Tokens;
444+
new (...args: Params): Service;
445+
},
446+
Params extends MapTokensToTypes<Services, Class["dependencies"]>,
447+
>(token: Token, cls: Class): Container<AddService<Services, Token, Service>> {
448+
return this.providesService(Injectable(token, cls.dependencies, (...args: Params) => new cls(...args)));
449+
}
433450

434451
/**
435452
* Registers a static value as a service in the container. This method is ideal for services that do not

‎src/__tests__/Container.spec.ts

+1
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ describe("Container", () => {
152152
}
153153
const containerWithService = container.providesClass("service", Item);
154154
expect(containerWithService.get("service")).toEqual(new Item(1));
155+
expect(containerWithService.factories.service().value).toBe(1);
155156
});
156157

157158
test("error if class constructor arity doesn't match dependencies", () => {

0 commit comments

Comments
 (0)
Please sign in to comment.