Search code examples
angulargraphqlapolloapollo-angular

Use interfaces to build graphql query


is it possible to build graphql queries using existing interfaces? or we should write same code twice)

for example in the doc we have

interface Post {
  id: string;
  title: string;
  ...

and then writing same fields in query

query allPosts {
      posts {
        id
        title
        ...

is there any way to write something like

query allPosts {
      posts: Post[]

Solution

  • It's not possible to do something like that because TypeScript types don't exist at runtime. Interfaces are also insufficient to represent GraphQL fields because they can't capture information like argument values or directive usage.

    You can, however, auto-generate TypeScript types from existing queries, which is what is normally done. See GraphQL Code Generator.