This is documentation for v11, which is no longer actively maintained.
For up-to-date documentation, see the latest version.

Unions

A union type represents a set of object types. It is very similar to an interface, except that there is no requirement for common fields between the specified types.

SDL
type TextContent {
text: String!
}
type ImageContent {
imageUrl: String!
height: Int!
}
union PostContent = TextContent | ImageContent

Clients can query fields returning a union like the following.

GraphQL
{
postContent {
... on TextContent {
text
}
... on ImageContent {
imageUrl
}
}
}

Learn more about unions here.

Usage

Unions can be defined like the following.

We can use a marker interface to define object types as part of a union.

C#
[UnionType("PostContent")]
public interface IPostContent
{
}
public class TextContent : IPostContent
{
public string Text { get; set; }
}
public class ImageContent : IPostContent
{
public string ImageUrl { get; set; }
public int Height { get; set; }
}
public class Query
{
public IPostContent GetContent()
{
// Omitted code for brevity
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddType<TextContent>()
.AddType<ImageContent>();
}
}