dotansimha / dotansimha/graphql-code-generator

TypeScript Resolvers: Easier way to get possible resolve types for interfaces

Open
#6,443 3 comments 2 reactions 0 assignees View on GitHub
core help wanted kind/enhancement
Dominant language
TypeScript
Stars
11.3k
Forks
1.4k
Avg merge
1d 1h
Merged PRs (30d)
23

Description

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

If you have an interface `Document` and multiple types implementing it, say `Article`, `Thesis` and `Other`, then the typescript resolvers generated looks similar to
```ts
export type DocumentResolvers = ResolversObject<{
__resolveType: TypeResolveFn<'Article' | 'Thesis' | 'Other', ParentType, ContextType>;
id?: Resolver;
....
}>;
```
As one can see, the implementing types are listed explicitly in the definition of the `__resolveType` function. Thus, they cannot easily be reused, which is mildly annoying if you want/need to use another function to return exactly one of the options (say because you need to parse or check other data to determine which of the types should be returned). A function like this would currently be annotated like
```ts
parse(input: any): 'Article' | 'Thesis' | 'Other'
```
This is prone to break in the future if other types implementing the interface are added, and leads to code duplication.

**Describe the solution you'd like**

Extract the possible type names to a separate type. Maybe even auto-generating something like
```ts
const DocumentResolveTypes = ['Article' | 'Thesis' | 'Other'] as const;
type DocumentResolveTypes = typeof DocumentResolveTypes [number];
```
so that one can easily iterate over the possible types.

**Describe alternatives you've considered**
I'm currently using the following code as a work-around.
```ts
type ResolveFnc> =
TResolver extends {
__resolveType: infer T
}
? T
: never

type ReturnType = T extends (...args: any[]) => infer R ? R : unknown
/**
* Type to extract the resolve type from a resolver for unions / interfaces.
*/
type ResolveType> = ReturnType<
ResolveFnc
>

ResolveType // 'Article' | 'Thesis' | 'Other'
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.