graphql-codegen-factories icon indicating copy to clipboard operation
graphql-codegen-factories copied to clipboard

Union factory has type error in certain scenarios

Open zhouzi opened this issue 2 years ago • 0 comments

When generating factories based on GitHub's GraphQL schema, I noticed errors for some union factories, e.g:

export function createBranchActorAllowanceActorMock(
  props: Partial<Types.BranchActorAllowanceActor> = {}
): Types.BranchActorAllowanceActor {
  switch (props.__typename) {
    case "Team":
      return createTeamMock(props);
    case "User":
      return createUserMock(props);
    case undefined:
    default:
      return createBranchActorAllowanceActorMock({
        __typename: "Team",
        ...props,
      });
  }
}

Types of property '__typename' are incompatible.   Type '"User" | "Team"' is not assignable to type '"User"'.     Type '"Team"' is not assignable to type '"User"'

It can be fixed this way:

export function createBranchActorAllowanceActorMock(
  props: Partial<Types.BranchActorAllowanceActor> = {}
): Types.BranchActorAllowanceActor {
  switch (props.__typename) {
    case "Team":
      return createTeamMock(props);
    case "User":
      return createUserMock(props);
    case undefined:
    default:
+    const { __typename, ...rest } = props;
      return createBranchActorAllowanceActorMock({
        __typename: "Team",
+       ...rest,
-        ...props,
      });
  }
}

For most them it's fine but sometimes it fails. Not sure why yet.

zhouzi avatar May 22 '22 19:05 zhouzi