API 设计 / 系统课时
使用 Interface 与 Union
使用 Interface 与 Union
当一个查询入口可能返回多种对象时,关键不是“能不能混在一起”,而是这些对象是否存在稳定的共同字段。本课用可运行的 GraphQL.js 示例区分 Interface 与 Union,并演示客户端如何通过抽象类型安全地读取具体字段。
学习目标
- 根据是否存在共同字段选择 Interface 或 Union
- 为抽象类型提供可解析的具体类型信息
- 使用片段与内联片段查询不同实现类型的字段
先判断共同契约是否存在
Interface 表达“这些类型都承诺提供一组共同字段”。例如文章和商品都可以视为内容,都有 id 与 title。客户端只依赖这两个字段时,不必知道实际拿到哪一种内容。
Union 只表达“结果可能是这些类型之一”,不要求成员共享字段。搜索结果同时包含文章和商品很常见,但 GraphQL 不允许直接在 Union 上选择成员字段;客户端必须先用内联片段进入具体类型。
| 需求 | Interface | Union |
|---|---|---|
| 多个类型有稳定共同字段 | 适合 | 可以,但会丢失共同契约 |
| 成员类型彼此异构 | 不适合强行抽象 | 适合 |
| 在抽象类型上直接查询共同字段 | 可以 | 不可以 |
| 成员必须显式声明关系 | implements |
由 Union 列出成员 |

用一个 Schema 同时观察两者
下面的示例使用 graphql 包。项目中需要已安装该依赖,脚本保存为 index.mjs 后即可运行。
import { buildSchema, graphql } from "graphql";
const schema = buildSchema(`
interface Content {
id: ID!
title: String!
}
type Product implements Content {
id: ID!
title: String!
price: Int!
}
type Article implements Content {
id: ID!
title: String!
excerpt: String!
}
union SearchResult = Product | Article
type Query {
content(id: ID!): Content
search: [SearchResult!]!
}
`);
const items = [
{ __typename: "Product", id: "p1", title: "Keyboard", price: 499 },
{ __typename: "Article", id: "a1", title: "GraphQL Tips", excerpt: "Use fragments." }
];
const rootValue = {
content: ({ id }) => items.find((item) => item.id === id) ?? null,
search: () => items
};
const source = `
query {
content(id: "p1") {
id
title
... on Product { price }
}
search {
__typename
... on Product { id title price }
... on Article { id title excerpt }
}
}
`;
const result = await graphql({ schema, source, rootValue });
console.log(JSON.stringify(result, null, 2));预期输出:
{
"data": {
"content": {
"id": "p1",
"title": "Keyboard",
"price": 499
},
"search": [
{
"__typename": "Product",
"id": "p1",
"title": "Keyboard",
"price": 499
},
{
"__typename": "Article",
"id": "a1",
"title": "GraphQL Tips",
"excerpt": "Use fragments."
}
]
}
}这里直接返回 __typename,GraphQL.js 的默认抽象类型解析器就能确定对象是 Product 还是 Article。在真实服务中也可以为 Interface 或 Union 提供显式的类型解析逻辑,但无论采用哪种方式,服务端都必须能把运行时对象映射到 Schema 中的具体对象类型。
客户端查询抽象类型的规则
查询 Content 时,id、title 属于 Interface 本身,因此可以直接选择;price 只属于 Product,必须放进 ... on Product 内。这个规则使共同契约保持稳定,同时允许实现类型继续扩展自己的字段。
查询 SearchResult 时,除了 __typename 这类元字段,业务字段都要放在具体类型的内联片段或命名片段中。客户端通常先读取 __typename,再根据类型渲染不同组件,这比靠某个可空字段猜类型更可靠。
选择 Interface 还是 Union
如果调用方需要围绕一组共同字段做分页、缓存、权限或通用展示,优先设计 Interface;如果查询只是在一个入口聚合若干彼此独立的结果类型,Union 更自然。两者都属于抽象类型,但 Interface 强调可依赖的共同能力,Union 强调有限的类型集合。