Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(types): functions must be wrapped in functions #7

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading