GraphQL types, generics and NestJS Type<>: not assignable to Type<>

111 views Asked by At

I am trying to call this definition:

import { GraphQLScalarType } from 'graphql';
import { Type } from '@nestjs/common';

export function createFilterClass<T extends typeof GraphQLScalarType>(
  FilterType: Type<T>
) {
  // ...
}

But all my attempts are failing:

import { GraphQLString } from 'graphql';
import { createFilterClass } from './filter-class';

const c = createFilterClass(GraphQLString);

/* Argument of type 'GraphQLScalarType<string, string>' is
   not assignable to parameter of type 'Type<typeof GraphQLScalarType>'.

   Type 'GraphQLScalarType<string, string>' is missing the following
   properties from type 'Type<typeof GraphQLScalarType>':
   apply, call, bind, prototype, and 4 more. ts(2345)
*/

const c = createFilterClass(GraphQLString);

/* Argument of type 'string' is not assignable to
   parameter of type 'Type<typeof GraphQLScalarType>'.

   Type 'string' is not assignable to type 'Type<typeof GraphQLScalarType>'. ts(2345)
*/

Note that I need to do Type<T> inside of createFilterClass, because otherwise this line will fail:

    @Field(() => FilterType, { nullable: true }) // Argument of type '{ nullable: true; }' is not assignable to parameter of type 'FieldOptionsExtractor<T>'. ts(2345)
    myField?: T;
1

There are 1 answers

0
Simeon On

Found out how to get this to compile, by doing:

createFilterClass<T extends GraphQLScalarType>(FilterType: T) { ... }

in combination with this wicked cast:

@Field(() => FilterType.constructor as Type<T>, { nullable: true })