Tom Bird
Tom Bird

Reputation: 1039

I need a type for a graphql property that could be two 2 types

So I have some code like the following:

input Data {
  activityValue: Int
}

But I need it to be something more like

input Data {
  activityValue: Int | String!
}

I know in typescript, even though frowned upon you can use any or number | string. Is there anything like this in graphql?

Upvotes: 2

Views: 5545

Answers (1)

FloWy
FloWy

Reputation: 984

There is no real such thing as multiple types in the GraphQL specification. However, Unions can fit your needs.

From the specification:

GraphQL Unions represent an object that could be one of a list of GraphQL Object types, but provides for no guaranteed fields between those types.

That means that Unions can include types but no scalars or lists.

For example, a union can be declared like this:

union Media = Book | Movie

And then be used as a type:

type Query {
  allMedia: [Media] # This list can include both Book and Movie objects
}

Example is taken from Apollo Docs.

If you want to check in your query if you have some type of the Union type, then you need to do that with inline fragments.

query Test {
  singleMedia(id: 123) {
    name
    ... on Book {
      author
    }
    ... on Movie {
      musicTitle
    }
  }
}

Upvotes: 2

Related Questions