Typing a GraphQL query with mandatory variable with TypeScript

Viewed 437

Is there a way with TypeScript (or any other tool) to throw an error at compile/build time if I'm using a GraphQL query without passing a required variable?

For instance, I have this GraphQL query:

query booksByAuthor($author: String!) {
  books(author: $author) {
    title
    year
  }
}

these TS types:

interface Book {
  title: string;
  year: number;
}

interface BooksByAuthorType {
  books: [Book];
}

interface BooksByAuthorVariables {
  author: string;
}

and this React component (fetching data with @apollo/react-hooks):

const Books = () => {
  const { data } = useQuery<
    BooksByAuthorType,
    BooksByAuthorVariables
  >(query); // notice I'm not passing `author` here

  return (
    <ul>
      {data.books.map(
        book => <li>{`${book.name} (${book.year})`}</li>
      )}
    </ul>
  );
}

How do I use TypeScript (or any other tool) in order to have an error in this case?

0 Answers
Related