ff-ioc
Fail-fast IoC container powered by typechecking from TypeScript
ff-ioc
aims to introduce a simple yet enforced way to declare dependency graph: as long as using well type-defined providers, no dependency mistake can be escaped from the TypeScript complier.
Get Started
Supposed there is a UserService
and a FriendService
, which can be defined as below:
FriendService
depends on the UserService
for retrieving user information. Based on the definition of this dependency, their provider functions can be defined as below:
; ;
We can now implement both service providers based on above type-defs:
;
Use createContainer
to create an IoC container and bind all providers to it:
; ; container.friendService.getFriendsOfUser'xxxxxxx'.then...;
Concept of Fail-fast
The ability of fail-fast comes from TypeScript by the following type definition:
;
T
is the generic type of container. It is inferred from ProviderMap<T>
when calling createContainer(providerMap)
:
;
This means when you have ProviderMap<T>
as the following type:
TypeScript will infer T
as the following type:
It then uses T
to declare the first parameter of associated provider functions, which builds up a junction between the container type and dependency type expected by each provider. If the container type is not a supertype of one of the provider dependency, there will be a compile error:
; ; // TypeScript Error: Type 'Console' provides no match for the signature '(msg: string): void'