How do you type partial types in a TypeScript Angular application using an Apollo backend?

99封情书 提交于 2019-12-07 10:33:30

You could define:

type MyComponentPerson = Pick<Person, "firstName" | "age">;

If you want to automatically generate this type based on the query, something like Type gql-tag in TypeScript might work for you. If that solution isn't quite right, please provide an example of your query and I may be able to help.

Because GraphQL schema can be statically analyzed there's no need to write interfaces by hand, at all. There are many tools that does it for you.

My team's work is heavily based on GraphQL and we use GraphQL Code Generator. Instead of writing interfaces by hand and then picking from it some fields you use that tool and you get all the types and interfaces that you might need.

https://github.com/dotansimha/graphql-code-generator

It creates a type specific to your query. If you fetch only firstName and age it will create type with only that.


But there's even better way of using Apollo and generating types. Instead of wrapping a query with gql tag, then generating and attaching types to it. You can use GraphQL Code Generator in combination with library that I wrote, Apollo Angular.

The idea is to let you write only queries, in .graphql files so you get full IDE support (autocompletion, validation etc) and codegen generates a ready to use service, that is strongly typed.

An example, you write query:

query MyFeed {
  feed {
    id
    name
  }
}

Next, you run codegen and in return you get an angular service called MyFeedGQL:

import { MyFeedGQL } from './graphql';

class AppComponent {
  constructor(myFeed: MyFeedGQL) {
    this.myFeed.watch().valueChanges.subscribe(() => ...);
  }
}

You no longer have to define types in Apollo thanks to that.

Here's an article about it: https://medium.com/the-guild/apollo-angular-code-generation-7903da1f8559

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!