From ac0a71eae8dd293f4b5e0a1173b72037752cffa3 Mon Sep 17 00:00:00 2001 From: Ghislain Thau Date: Wed, 9 Mar 2022 11:27:36 +0100 Subject: [PATCH] Created a typescript utility type to extract the target (generic) type of an injection token. This allows to write injected dependencies like: - given the following injection token: ```ts const MyToken = new InjectionToken>>('my-token'); ``` you can write: ```ts type MyTokenTargetType = InjectionTokenTargetType; class MyClass { constructor(@Inject(MyToken) someField: MyTokenTargetType) {} } ``` instead of: ```ts const MyToken = new InjectionToken>>('my-token'); class MyClass { constructor(@Inject(MyToken) someField: Promise>) {} } ``` --- packages/graphql-modules/src/di/index.ts | 1 + packages/graphql-modules/src/di/providers.ts | 4 ++++ packages/graphql-modules/src/index.ts | 1 + website/docs/di/providers.mdx | 12 ++++++++++++ 4 files changed, 18 insertions(+) diff --git a/packages/graphql-modules/src/di/index.ts b/packages/graphql-modules/src/di/index.ts index 18ff2ddd01..58067e6072 100644 --- a/packages/graphql-modules/src/di/index.ts +++ b/packages/graphql-modules/src/di/index.ts @@ -2,6 +2,7 @@ export { Injectable, Optional, Inject, ExecutionContext } from './decorators'; export { forwardRef } from './forward-ref'; export { InjectionToken, + InjectionTokenTargetType, Type, Provider, AbstractType, diff --git a/packages/graphql-modules/src/di/providers.ts b/packages/graphql-modules/src/di/providers.ts index 7ef34ab0d7..7da25dd0a7 100644 --- a/packages/graphql-modules/src/di/providers.ts +++ b/packages/graphql-modules/src/di/providers.ts @@ -11,6 +11,10 @@ export class InjectionToken { } } +export type InjectionTokenTargetType = T extends InjectionToken + ? U + : never; + export function isToken(v: any): v is InjectionToken { return v && v instanceof InjectionToken; } diff --git a/packages/graphql-modules/src/index.ts b/packages/graphql-modules/src/index.ts index 2ecd92fd5e..5404651835 100644 --- a/packages/graphql-modules/src/index.ts +++ b/packages/graphql-modules/src/index.ts @@ -24,6 +24,7 @@ export { TypeProvider, forwardRef, InjectionToken, + InjectionTokenTargetType, Scope, } from './di'; diff --git a/website/docs/di/providers.mdx b/website/docs/di/providers.mdx index 26fef1c92b..731fd9167a 100644 --- a/website/docs/di/providers.mdx +++ b/website/docs/di/providers.mdx @@ -307,6 +307,18 @@ class Posts { > `@Inject` decorator is needed because of limitation of type system. +In order to avoid repeating the target type of an injection token when a injecting dependency through the constructor, the utility type `InjectionTokenTargetType` can be used. The previous code sample can be rewritten in the following manner: + +```typescript +import { Injectable, Inject, InjectionTokenTargetType } from 'graphql-modules' +import { ApiKey } from './keys' + +@Injectable() +class Posts { + constructor(@Inject(ApiKey) private key: InjectionTokenTargetType) {} +} +``` +