From d8085bda48cef53d31ec199e6bde05cfa1dece14 Mon Sep 17 00:00:00 2001 From: Elias Coronado Date: Fri, 30 Aug 2024 10:20:28 -0700 Subject: [PATCH] Helper type to extract valid keys from container instance Given a container instance, I want to have interfaces that require a valid type from the container. I could create MyServices type of valid keys, pass it to the container and then require a keyof MyServices.. but it's easier to allow the container to build the types and extract it from it: ``` interface MyServices { foo: number; bar: string; } type ValidServices = keyof MyServices; interface Plugin { key: ValidServices; } const container = new Container({}) ``` vs ``` const container = new Container({}) type ValidServices = ContainerKeys; interface Plugin { key: ValidServices; } ``` --- src/Container.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Container.ts b/src/Container.ts index 0694c34..584c8c4 100644 --- a/src/Container.ts +++ b/src/Container.ts @@ -36,6 +36,14 @@ export type ContainerToken = typeof CONTAINER; type ArrayElement = A extends readonly (infer T)[] ? T : never; +type ReturnTypeOfFactories = T extends { factories: infer R } ? R : never; + +/** + * Helper type for extracting valid keys from a container instance + */ +export type ContainerKeys = keyof ReturnTypeOfFactories; + + /** * Represents the dependency injection container that manages the registration, * creation, and retrieval of services. The Container class is central to