Skip to Content
Gqlts

Unions and interfaces

Use generated on_TypeName fields to select GraphQL union and interface members. Always request __typename when you plan to narrow the result at runtime.

Select member fields

import { createClient } from './generated'; const client = createClient(); const { data } = await client.query({ account: { __typename: true, commonProp: true, on_User: { id: true, name: true, }, on_Guest: { surname: true, }, }, }); data?.account?.commonProp;

Narrow with __typename

TypeScript can narrow the generated union when you compare __typename.

const { data } = await client.query({ account: { __typename: true, on_User: { id: true, name: true, }, }, }); if (data?.account?.__typename === 'User') { data.account.id; data.account.name; }

Use generated type guards

Generated clients export is<TypeName> helpers for union and interface members.

import { createClient, isGuest, isUser } from './generated'; const client = createClient(); const { data } = await client.query({ account: { __typename: true, on_User: { id: true, name: true, }, on_Guest: { surname: true, }, }, }); if (isUser(data?.account)) { data.account.name; } if (isGuest(data?.account)) { data.account.surname; }

Type guards require __typename. If the field is missing, the guard cannot know which runtime type it received.