Not typing or manually maintaining the data-types can lead to many issues:
outdated typing (regarding the current Schema)
typos
partial typing of data (not all Schema’s fields has a corresponding type)
For this reason, GraphQL Code Generator provides a @graphql-codegen/typescript-apollo-angular
plugin that generates typed Apollo services for each GraphQL operation.
Just a few configuration steps are required to get those Apollo services:
Install
npm i graphqlnpm i -D typescriptnpm i -D @graphql-codegen/clinpm i -D @graphql-codegen/typescriptnpm i -D @graphql-codegen/typescript-operationsnpm i -D @graphql-codegen/typescript-apollo-angular
Assuming that, as recommended, your package.json has the following script:
package.json
{ "scripts": { "generate": "graphql-codegen" }}
Running the following generates the graphql/generated.ts file.
npm run generate
yarn generate
pnpm run generate
bun run generate
We can now update our code as follows:
// BE SURE TO USE Observable from `rxjs` and not from `@apollo/client/core` when using mapimport { Observable } from 'rxjs'import { map } from 'rxjs/operators'import { PostsGQL, PostsQuery } from './graphql'@Component({ /* … */})export class PostsComponent { posts: Observable<PostsQuery['posts']> constructor(postsGQL: PostsGQL) { this.posts = postsGQL.watch().valueChanges.pipe(map(result => result.data.posts)) }}