molszanski / iti

~1kB Dependency Injection Library for Typescript and React with a unique support of async flow
https://itijs.org
MIT License
127 stars 6 forks source link

Improve type inference on `getContainerSet` #44

Open arthur-fontaine opened 3 months ago

arthur-fontaine commented 3 months ago

Is your feature request related to a problem? Please describe.

Considering the following code.

const a = await root.getContainerSet(["userManual", "oven"])
a.oven // There is no error, oven exists, the type in compile-time is the same that the type in run-time

const b = await root.getContainerSet(() => ["userManual"])
b.oven // There is no error, BUT oven DOES NOT exist, the type in compile-time is NOT the same that the type in run-time

It is a problem in this example:

const kitchenContainer = async ({ oven, userManual }) => {
  await oven.preheat()
  return {
    kitchen: new Kitchen(oven, userManual),
  }
}

const node = root.add((ctx, node) => ({
  kitchen: async () =>
    kitchenContainer(await node.getContainerSet(["userManual"])),
}))

We are requiring from kitchenContainer two dependencies: over and userManual. But we are only providing userManual. This will cause an error at run-time.

Describe the solution you'd like

The returned type of getContainerSet should be automatically inferred from what we pass in parameter.

Solution

(tested and it works)

Edit these lines https://github.com/molszanski/iti/blob/0a3a006113b4176316c308805314a135c0f47902/iti/src/iti.ts#L371-L373 to

 public async getContainerSet<T extends keyof Context>( 
   tokensOrCb: Pick<KeysOrCb<Context>, T>, 
 ) { 

(This solution may be applicable to other functions like subscribeToContainerSet and _extractTokens too)

Note: We can improve the type printing (on hovering on VSCode for example), by wrapping the Pick<...> into the Prettify helper.

type Prettify<T> = {
  [K in keyof T]: T[K];
} & {};
With PrettifyWithout Prettify
Capture d’écran 2024-04-06 à 02 54 27 Capture d’écran 2024-04-06 à 02 54 44
loicnestler commented 4 weeks ago

Any updates on this? 👀

arthur-fontaine commented 4 weeks ago

@loicnestler The repo seems to be dead (last commit was 2 years ago). I created Diabolo to get type-safe DI, but it is not based on the concept of containers.

molszanski commented 1 week ago

Will get back to the repo this summer 🤞 Got stuck on ESM / CJS migration 😮‍💨

molszanski commented 1 week ago

Sorry for letting everyone down :(