Skip to content

Function: createUnionType()

ts
function createUnionType<T>(options): (...args) => InstanceType<T[number]>;

Defined in: packages/apollo/src/helpers/create-union-type.ts:28

Creates a GraphQL Union type from the given options. The returned class can be used as a @Field(() => UnionType) type.

Type Parameters

Type ParameterDescription
T extends readonly (...args) => object[]Tuple of union member constructors.

Parameters

ParameterTypeDescription
options{ description?: string; name: string; resolveType?: (value) => string | ((...args) => object) | null | undefined; types: () => T; }Union type configuration.
options.description?stringDescription of the union type.
options.namestringName of the union type in the GraphQL schema.
options.resolveType?(value) => string | ((...args) => object) | null | undefinedFunction to determine the concrete type of a resolved value. May return a type name string or a class constructor from the union.
options.types() => TFactory function returning array of types in the union.

Returns

A class that can be used as a GraphQL union type.

(...args) => InstanceType<T[number]>

Example

typescript
export const SearchResult = createUnionType({
  name: 'SearchResult',
  types: () => [User, Post] as const,
  resolveType(value) {
    return 'name' in value ? User : Post;
  },
});

@Query(() => [SearchResult])
async search(@Args('query') query: string) {
  return this.searchService.search(query);
}

Released under the MIT License.