TExcelTAD
Home › GraphQL › Lists & Non-Null

Lists & Non-Null

Every type in GraphQL can be wrapped by two modifiers:

  • [T] makes it a list of T.
  • T! makes it non-null: the value can never be null.

By default, every field is nullable. That's a deliberate design choice: if one field fails, the server can return null for it and still deliver the rest of the response.

Reading the combinations

Type The list itself Items in the list
[String] may be null may be null
[String!] may be null never null
[String]! never null may be null
[String!]! never null never null

[String!]! is the most common choice for lists: "always a list (maybe empty), and no holes in it".

Non-null outputs are a promise

When a field is declared non-null, the server promises a value. If a resolver returns null anyway, that's a server bug, and GraphQL reports it:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type User {
    name: String!
    nickname: String
  }
  type Query { user: User }
`);

const rootValue = {
  user: { name: 'Margaret', nickname: null },
};

let result = await graphql({ schema, source: '{ user { name nickname } }', rootValue });
console.log(JSON.stringify(result));

rootValue.user = { name: null, nickname: 'Maggie' };
result = await graphql({ schema, source: '{ user { name nickname } }', rootValue });
console.log(JSON.stringify(result.data));
console.log(result.errors[0].message);
{"data":{"user":{"name":"Margaret","nickname":null}}}
{"user":null}
Cannot return null for non-nullable field User.name.

In the second run name was null, which String! forbids. Look closely at data: not only name is gone, the whole user object became null.

Null propagation

When a non-null field can't produce a value, the null "bubbles up" to the nearest nullable parent. Every field between them is lost. This keeps the promise: a client that reads user.name either gets a string or sees user itself is null.

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Item { label: String! }
  type Query {
    nullableItems: [Item]
    strictItems: [Item!]
    strictList: [Item!]!
  }
`);

const items = [{ label: 'ok' }, { label: null }, { label: 'fine' }];
const rootValue = { nullableItems: items, strictItems: items, strictList: items };

for (const field of ['nullableItems', 'strictItems']) {
  const result = await graphql({ schema, source: `{ ${field} { label } }`, rootValue });
  console.log(field, JSON.stringify(result.data));
}

const result = await graphql({ schema, source: '{ strictList { label } }', rootValue });
console.log('strictList', JSON.stringify(result.data));
nullableItems {"nullableItems":[{"label":"ok"},null,{"label":"fine"}]}
strictItems {"strictItems":null}
strictList null
  • [Item]: only the broken item became null.
  • [Item!]: items can't be null, so the whole list became null.
  • [Item!]!: the list can't be null either, so the null bubbled up to data itself.

Non-null arguments are requirements

On inputs the meaning flips: ! says "the client must provide this". Here search(term: String!, tags: [String!]) requires a term, while tags is optional, but if it's given, it may not contain null:

js · try it yourself
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(`
  type Query { search(term: String!, tags: [String!]): [String!]! }
`);

const words = ['graph', 'graphic', 'paragraph', 'photo'];
const rootValue = {
  search: ({ term, tags }) => {
    const hits = words.filter((w) => w.includes(term));
    return tags ? hits.map((w) => `${w} ${tags.join(',')}`) : hits;
  },
};

for (const source of [
  '{ search(term: "graph") }',
  '{ search(term: "ph", tags: ["x"]) }',
  '{ search(term: null) }',
  '{ search(term: "a", tags: ["x", null]) }',
]) {
  const result = await graphql({ schema, source, rootValue });
  console.log(result.errors ? result.errors[0].message : JSON.stringify(result.data.search));
}
["graph","graphic","paragraph"]
["graph x","graphic x","paragraph x","photo x"]
Expected value of type "String!", found null.
Expected value of type "String!", found null.

A single value where a list is expected

For convenience, input coercion wraps a single value in a list: tags: "x" is accepted as ["x"]. Output lists aren't converted: a resolver for [String] must return an array (or any iterable).

Choosing nullability

Make it non-null (!) when… Keep it nullable when…
the value always exists (id, createdAt) it comes from another service that may fail
a missing value would be a bug it's genuinely optional (middleName)
it's a list that can just be empty you might remove or restrict it later

Tip: Changing nullable → non-null on an output field is safe for clients; the opposite breaks clients that relied on the promise. When unsure, start nullable. For arguments it's reversed: making a required argument optional is safe, making an optional one required breaks existing queries.

Test yourself

Which type means 'a list that is never null, whose items may be null'?

  1. [String!]
  2. [String]!
  3. [String!]!
  4. [String]

A resolver returns null for a String! field on a nullable user object. What happens?

  1. The field is null
  2. user becomes null and an error is reported
  3. The server crashes
  4. The field is omitted silently

What does ! mean on an argument like term: String!?

  1. The resolver must return a value
  2. The client must provide a non-null value
  3. The argument is deprecated
  4. The argument has a default