Skip to content

Unions and enums

Register a TypeScript enum as a GraphQL enum with EnumType, and model union-like results with an object type.

2 min read Source

Enums

A TypeScript enum is an object, not a class, so it cannot carry a decorator. Register it with EnumType and give it an explicit GraphQL name — a numeric enum has no readable runtime name:

import {EnumType, ObjectType, Field} from "@typeix/resty-graphql";

export enum Role {
  Admin,
  User
}

EnumType(Role, {name: "Role", description: "User role"});

@ObjectType()
class UserDto {
  @Field()
  id: string;

  @Field(() => Role)
  role: Role;
}

EnumType returns the enum object, so it can wrap a declaration:

export enum RoleEnum {
  Admin,
  User
}

export const Role = EnumType(RoleEnum, {name: "Role"});

The generated schema contains:

enum Role {
  Admin
  User
}

An enum can be used as an output field type, an input field type and an argument type.

Unions

Union output types are not implemented in the current adapter. Only object types and input types are generated. Model a union as a single object type with a discriminator field, or expose separate queries:

@ObjectType()
class SearchResult {
  @Field()
  kind: string;        // "book" | "author"

  @Field({nullable: true})
  book?: Book;

  @Field({nullable: true})
  author?: Author;
}

Interfaces

GraphQL interfaces are not implemented either. Use an object type shared through composition, or duplicate the common fields on each type. @ObjectType inheritance in TypeScript does not create a GraphQL interface.