Skip to content

Commit

Permalink
feat(types): functions must be wrapped in functions (#7)
Browse files Browse the repository at this point in the history
* feat(types): functions must be wrapped in functions

* review

* fix union bug

---------

Co-authored-by: Marc Vincenti <marc.vincenti@indy.fr>
  • Loading branch information
marcvincenti and marc-indy authored Oct 19, 2024
1 parent cb9099c commit 0f14724
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,18 @@ export type ProviderFn<
? (externalDeps?: ProviderFnArgs<Registry>) => ModuleAPI<Registry, PublicAPI>
: (externalDeps: ProviderFnArgs<Registry>) => ModuleAPI<Registry, PublicAPI>;

/**
* If the injectable is a function, we have to wrap it in a function to avoid treating it as a factory
*/
type WrapFunctionInjectable<T> = [T] extends [(...args: any[]) => any]
? (deps?: any) => T
: ((deps?: any) => T) | T;

/**
* Checks if each injectable match the required dependencies of the entire registry
*/
type ValidateRegistry<Registry extends ObjectLike, Deps = FlatDependencyTree<Registry>> = {
[key in keyof Registry]: key extends keyof Deps ? ((deps?: any) => Deps[key]) | Deps[key] : Registry[key];
[key in keyof Registry]: key extends keyof Deps ? WrapFunctionInjectable<Deps[key]> : Registry[key];
};

declare function valueFn<T>(value: T): () => T;
Expand Down
11 changes: 10 additions & 1 deletion src/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
Injectable,
InjectableMap,
ProviderFn,
WrapFunctionInjectable,
} from './index';
import {
createProvider,
Expand Down Expand Up @@ -178,6 +179,11 @@ lateBoundDependencies: {
};
}

wrapFunctionInjectable: {
// test that () => SomeUnionType is assignable to WrapFunctionInjectable<SomeUnionType>
let unionInjectable: WrapFunctionInjectable<'a' | 'b'> = (): 'a' | 'b' => 'a';
}

publicAPI: {
let publicAPI: ProviderFn<
{
Expand Down Expand Up @@ -207,12 +213,15 @@ createProvider: {
injectables: {
foo: ({ a }: { a: number }) => a,
bar: ({ b }: { b: string }) => b,
baz: ({ c }: { c: () => boolean }) => c(),
// @ts-expect-error a is not a number
a: "42",
// @ts-expect-error b is not a string
b: () => 42 as number,
// @ts-expect-error c has to be wrapped in a function
c: () => true,
},
api: ['foo', 'bar'],
api: ['foo', 'bar', 'baz'],
});

createProvider({
Expand Down

0 comments on commit 0f14724

Please sign in to comment.