Skip to content

GraphQL to Flow Types Conversion — Numio

Generates Flow type definitions from a GraphQL schema and operations using @graphql-codegen/flow and flow-operations. Object types become exact Flow objects ({| |}) and nullable fields become optional maybe types (?T).

Adding typed GraphQL results to a codebase that still type-checks with Flow instead of TypeScript.

GraphQL Schema

Document

When to use it

  • Adding typed GraphQL results to a codebase that still type-checks with Flow instead of TypeScript.
  • Generating variables and result types for a single query to paste next to a component.

How to use

  1. Paste the schema SDL into the GraphQL Schema editor.
  2. Enter the operations you use in the Document editor, or clear it if you only need schema types.
  3. Copy the output, which begins with // @flow, into a .js file under Flow.

GraphQL schema + document

# GraphQL Schema editor
type Query {
  user(id: ID!): User
}

type User {
  id: ID!
  name: String
  tags: [String!]!
}

# Document editor
query GetUser($id: ID!) {
  user(id: $id) { id name }
}

Flow types

// @flow
…
export type User = {|
  __typename?: "User",
  id: $ElementType<Scalars, "ID">,
  name?: ?$ElementType<Scalars, "String">,
  tags: Array<$ElementType<Scalars, "String">>,
|}

export type GetUserQueryVariables = {
  id: $ElementType<Scalars, "ID">,
}

export type GetUserQuery = {
  ...{ __typename?: "Query" },
  ...{|
    user?: ?{
      ...{ __typename?: "User" },
      ...$Pick<User, {| id: *, name?: * |}>,
    },
  |},
}

Details and limitations

Fields reference scalars through $ElementType<Scalars, "ID">; the Scalars type at the top (omitted above) maps ID and String to string, Int and Float to number.

Operation result types are built from object spreads and a local $Pick helper, so only the selected fields appear.

Generation runs in a Web Worker in your browser and the result is formatted with Prettier; there are no plugin options on the page.

FAQ

Are the generated object types exact?

Yes. Schema object types use exact object syntax {| ... |}, so extra properties are rejected by Flow.

How are nullable fields represented?

A nullable field becomes an optional property with a maybe type, for example name?: ?$ElementType<Scalars, "String">. Non-null fields are required and non-maybe.

Why does the output contain a "Document ignored" comment?

Operations in the Document editor are validated against the schema. If they do not match (the default example queries username), only schema types are generated and the first error appears as a comment below // @flow. Adjust or clear the document.

Specifications and references