跳到主要内容

动态类型:GraphQL To Flow类型 — Numio

使用 @graphql-codegen/flow 和 flow-operations,根据 GraphQL schema 和操作生成 Flow 类型定义。对象类型变为精确的 Flow 对象({| |}),可空字段变为可选的 maybe 类型(?T)。

为仍使用 Flow 而非 TypeScript 做类型检查的代码库添加带类型的 GraphQL 结果。

GraphQL Schema

Document

适用场景

  • 为仍使用 Flow 而非 TypeScript 做类型检查的代码库添加带类型的 GraphQL 结果。
  • 为单个查询生成变量和结果类型,放在组件旁边使用。

使用方法

  1. 将 schema SDL 粘贴到 GraphQL Schema 编辑器。
  2. 在 Document 编辑器中输入要用到的操作;如果只需要 schema 类型,可将其清空。
  3. 复制以 // @flow 开头的输出,放入受 Flow 检查的 .js 文件中。

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 类型

// @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?: * |}>,
    },
  |},
}

功能与限制

字段通过 $ElementType<Scalars, "ID"> 引用标量;顶部的 Scalars 类型(上例中已省略)将 ID 和 String 映射为 string,将 Int 和 Float 映射为 number。

操作结果类型由对象展开和本地的 $Pick 辅助类型构成,因此只包含选中的字段。

生成在浏览器的 Web Worker 中运行,结果用 Prettier 格式化;页面上没有插件选项。

FAQ

生成的对象类型是精确类型吗?

是。schema 中的对象类型使用精确对象语法 {| ... |},多余的属性会被 Flow 拒绝。

可空字段如何表示?

可空字段变为带 maybe 类型的可选属性,例如 name?: ?$ElementType<Scalars, "String">。非空字段为必填且不是 maybe 类型。

为什么输出中有 "Document ignored" 注释?

Document 编辑器中的操作会按 schema 校验。如果不匹配(默认示例查询了 username),则只生成 schema 类型,第一条错误以注释形式出现在 // @flow 下方。请修改或清空 document。

规范与参考资料