The Generated AllBooksQuery Type
Learn about the AllBooksQuery type, generated using GraphQL Code Generator.
The generated AllBooksQuery
type and the old AllBooksQuery
type
Another generated type in the src/generated/graphql.tsx
file that we should focus on is the AllBooksQuery
type.
export type AllBooksQuery = ({ __typename?: 'Query' }& { books: Array<({ __typename?: 'Book' }& Pick<Book, 'title'>)>});
type AllBooksQuery = {books: Book[];};
Well, almost. The difference between the two is that the generated AllBooksQuery only accepts objects of the Book type that have a title and no other fields. This generated type expects title because that is the only field we’re querying for in our allBooks query, as shown in the code below:
const allBooksQuery = gql`query allBooks {books {title}}`;
The generated AllBooksQuery
type uses Pick
, which is TypeScript code for, “Give me the type of Book
, but only the ones with these fields.” This means that a response with this shape would be valid according to the BooksQuery
type.
{__typename: 'Query',books: [{__typename: 'Book',title: 'Active Rails'}}
But a response with an extra field such as author
or id
, like in the code snippet below, would be invalid since we’re limiting the fields of Book
to just title
.
{__typename: 'Query',books: [{__typename: 'Book',id: '1',title: 'Active Rails'}}
These types ...