Urigo / graphql-modules

Enterprise Grade Tooling For Your GraphQL Server

Home Page:https://graphql-modules.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Utility type to extract InjectionToken target type and avoid repetition

gthau opened this issue · comments

commented

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

When doing dependency injection in the constructor using an injection token, one has to know the target type of the injection token and repeat this type in the constructor, e.g.

const MyToken = new InjectionToken<Promise<Array<string | number>>>('my-token');

class MyClass {
  constructor(@Inject(MyToken) someField: Promise<Array<string | number>>) {}
}

Describe the solution you'd like

I'd like graphql-module to provide me with a utility type to extract the target type of the injection token.
Using this simple utility type:

export type InjectionTokenTargetType<T> = T extends InjectionToken<infer U>
  ? U
  : never;

one can rewrite the previous example like so:

type MyTokenTargetType = InjectionTokenTargetType<typeof MyToken>;

class MyClass {
  constructor(@Inject(MyToken) someField: MyTokenTargetType) {}
}

Describe alternatives you've considered

I have written this utility type in my project code. However I believe it'd beneficial to have it in graphql-modules. Such a type is not currently writeable as a generic Typescript type because Typescript doesn't natively support Higher-Kinded types (parametrized generic types).

Additional context

commented

Related PR: #2135