Skip to content

Interface and union fields are not optional #66

@mizdra

Description

@mizdra

Environment

typescript version: 5.4.2
@graphql-codegen/cli version: 5.0.2
@graphql-codegen/typescript version: 4.0.6
@mizdra/graphql-codegen-typescript-fabbrica version: 0.3.2

Summary

If you pass an interface or union to defaultFields that is missing some fields, tsc will throw a compile error.

type Query {
  node(id: ID!): Node
  search(query: String!): SearchResult
}
interface Node {
  id: ID!
}
union SearchResult = Article | User
type Article implements Node {
  id: ID!
  title: String!
}
type User implements Node {
  id: ID!
  name: String!
}
defineQueryFactory({
  defaultFields: {
    __typename: 'Query',
    // Missing fields such as `id`.
    // Expected no error, but got an error.
    node: {},
  },
});
defineQueryFactory({
  defaultFields: {
    __typename: 'Query',
    // Missing fields such as `id`.
    // Expected no error, but got an error.
    search: {},
  },
});

Step to reproduce

https://stackblitz.com/edit/playground-graphql-codegen-typescript-fabbrica-fdjpge?file=src%2Findex.test.ts

What did you expect to happen?

No typescript compile errors. The field should be allowed to be missing.

What actually happened?

Typescript compile error occurs.

Link to Minimal Reproducible Example

https://stackblitz.com/edit/playground-graphql-codegen-typescript-fabbrica-fdjpge?file=src%2Findex.test.ts

Participation

  • I am willing to submit a pull request for this issue.

Additional comments

The OptionalQuery type was as follows:

export type OptionalQuery = {
  __typename?: 'Query';
  node?: Query['node'] | undefined;
  search?: Query['search'] | undefined;
};

Perhaps this is wrong. The type should be as follows:

export type OptionalNode = OptionalArticle | OptionalUser;
export type OptionalSearchResult = OptionalArticle | OptionalUser;
export type OptionalQuery = {
  __typename?: 'Query';
  node?: OptionalNode | undefined;
  search?: OptionalSearchResult | undefined;
};

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions