nexus icon indicating copy to clipboard operation
nexus copied to clipboard

Calling "t.modify" makes modified field required even if has a custom resolver

Open VictorGlindasPaf opened this issue 2 years ago • 1 comments

Modifying a field on a type surprisingly modifies the generated "source type", on the object, even if the signature is the same. This causes typing errors in the parent field resolver.

import { interfaceType, objectType } from 'nexus';

export const Node = interfaceType({
  name: 'Node',
  definition(t) {
    t.nonNull.id('id', {
      resolve() {
        return '<example>';
      },
    });
  },
});

export const ChildObjectType = objectType({
  name: 'ChildObjectType',
  definition(t) {
    t.implements(Node);
    // Without this, there are no typing errors,
    // and the parent only needs to resolve "firstName" & "lastName".
    // But when added, it complains about the parent not passing "id" as well.
    t.modify('id', {
      resolve() {
        return '<modified-example>';
      },
    });
    t.nonNull.string('firstName');
    t.nonNull.string('lastName');
    t.nonNull.string('fullName', {
      resolve(source) {
        return `${source.firstName} ${source.lastName}`;
      },
    });
  },
});

export const ParentObjectType = objectType({
  name: 'ParentObjectType',
  definition(t) {
    t.field('child', {
      type: ChildObjectType,
      resolve() { // <-- This is where it throws a type error
        return {
          firstName: 'child',
          lastName: 'child',
        };
      },
    });
  },
});

Generated typescript output:

// Without modifying "id"
export interface NexusGenObjects {
  ChildObjectType: {
    firstName: string;
    lastName: string;
  }
}

// After modifying "id"
export interface NexusGenObjects {
  ChildObjectType: {
    id: string;
    firstName: string;
    lastName: string;
  }
}

VictorGlindasPaf avatar Jun 22 '22 13:06 VictorGlindasPaf

I'm experiencing the same thing. Found out that re-declaring the field on the subtype instead of using t.modify acts as a workaround.

larrifax avatar Oct 05 '22 09:10 larrifax