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

Typescript utility type to extract the target (generic) type of an injection token #2135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions packages/graphql-modules/src/di/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export { Injectable, Optional, Inject, ExecutionContext } from './decorators';
export { forwardRef } from './forward-ref';
export {
InjectionToken,
InjectionTokenTargetType,
Type,
Provider,
AbstractType,
Expand Down
4 changes: 4 additions & 0 deletions packages/graphql-modules/src/di/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export class InjectionToken<T> {
}
}

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

export function isToken(v: any): v is InjectionToken<any> {
return v && v instanceof InjectionToken;
}
Expand Down
1 change: 1 addition & 0 deletions packages/graphql-modules/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export {
TypeProvider,
forwardRef,
InjectionToken,
InjectionTokenTargetType,
Scope,
} from './di';

Expand Down
12 changes: 12 additions & 0 deletions website/docs/di/providers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof ApiKey>) {}
}
```

</TabItem>
</Tabs>

Expand Down