Skip to content

Commit

Permalink
Improve ServiceDefinition type
Browse files Browse the repository at this point in the history
  • Loading branch information
TiMESPLiNTER committed Jan 31, 2024
1 parent 78d90e3 commit 0826c30
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/pimple.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import ServiceProvider from "./serviceProvider";
type ProviderDeclaration<T> = (container: Pimple<T>) => void|ServiceProvider<T>;
type LazyServiceDefinition<T, S> = (container: Pimple<T>) => S;
type ProtectedServiceDefinition<T, S> = () => LazyServiceDefinition<T, S>;
type ServiceDefinition<T, S> = LazyServiceDefinition<T, S>|ProtectedServiceDefinition<T, S>|S;
type PlainServiceDefinition<S> = S extends Function ? () => S : S; // If a function, it needs to be wrapped/protected
type ServiceDefinition<T, S> = PlainServiceDefinition<S>|LazyServiceDefinition<T, S>|ProtectedServiceDefinition<T, S>|(S extends Function ? () => S : S);
type ServiceMap<T> = { [key in ServiceKey<T>]: ServiceDefinition<T, T[ServiceKey<T>]> };

/**
Expand Down Expand Up @@ -50,7 +51,7 @@ export default class Pimple<T> implements Container<T>
constructor(services: Partial<ServiceMap<T>> = {}) {
Object.keys(services).forEach((service) => {
const serviceKey = service as ServiceKey<T>;
this.set(serviceKey, services[serviceKey] as T[ServiceKey<T>]);
this.set(serviceKey, services[serviceKey] as ServiceDefinition<T, T[ServiceKey<T>]>);
}, this);
}

Expand Down Expand Up @@ -121,8 +122,8 @@ export default class Pimple<T> implements Container<T>
/**
* Register a protected function
*/
public protect<K extends ServiceKey<T>>(key: K, service: T[K]): () => T[K] {
return () => service;
public protect<K extends ServiceKey<T>>(func: T[K]): () => T[K] {
return () => func;
}

/**
Expand Down

0 comments on commit 0826c30

Please sign in to comment.