Apollo-tooling: generate types from all __typename

Created on 10 Jan 2018  路  5Comments  路  Source: apollographql/apollo-tooling

It would be great if every literal with a __typename could be exported as a standalone type

Current:

export type CharactersQuery = {
  characters: Array<{
    __typename: 'Human',
    name: string,
    homePlanet: ?string
  } | {
    __typename: 'Droid',
    name: string,
    primaryFunction: ?string
  }>
}

wanted:

export type Human = {
    __typename: 'Human',
    name: string,
    homePlanet: ?string
  } 

export type Droid {
    __typename: 'Droid',
    name: string,
    primaryFunction: ?string
  }
export type CharactersQuery = {
  characters: Array<Human | Droid>
}

Most helpful comment

I switched to https://github.com/dotansimha/graphql-code-generator, which does the job.

All 5 comments

This is exactly what I want for my Angular components.

@Component({
  selector: 'droid',
  templateUrl: './result.component.html',
  styleUrls: ['./result.component.sass']
})
export class ResultComponent {

  @Input() droid: Droid; << I want this!
}

It would likely need to reference the query name from your gql string such as: CharacterQueryDroid as the query return type can be a subset of Droid attributes.

How can I help make this happen?

looks like the typescript-modernoption is generating types like that, but at the moment is kinda broken, there are some PR already to fix problems, (buggy @babel/types version, generation of .js instead of .ts)

I switched to https://github.com/dotansimha/graphql-code-generator, which does the job.

@JohannesHoppe graphql-code-generator seems to work, thanks!

Going to close this out. The goal is to get the -modern targets to be the default targets once issues get sorted out and then we'll have it :)

Was this page helpful?
0 / 5 - 0 ratings