Skip to content

Scalars & Enums in GraphQL

GraphQL includes primitive types called scalars, and enumerated types called enums. These types form the foundation of how GraphQL defines and validates the shape of data.


Scalars

Scalars represent the leaf values in a GraphQL query — the fields that resolve to concrete values.

Built-in Scalar Types

Scalar Description
Int A 32-bit signed integer
Float A double-precision floating-point value
String A UTF-8 character sequence
Boolean A true or false value
ID A unique identifier (often a string)

Example

type User {
  id: ID!
  name: String!
  age: Int
  email: String
  isActive: Boolean!
}

Custom Scalars

You can define custom scalars for domain-specific values like Date, URL, Email, or JSON.

Schema Definition

scalar Date

type Event {
  id: ID!
  name: String!
  startTime: Date!
}

Server-Side Handling (Example in Apollo Server)

const { GraphQLScalarType } = require('graphql');

const DateScalar = new GraphQLScalarType({
  name: 'Date',
  serialize(value) {
    return value.toISOString();
  },
  parseValue(value) {
    return new Date(value);
  },
  parseLiteral(ast) {
    return new Date(ast.value);
  },
});

Custom scalars require implementation of how they’re serialized and parsed.


Enums

Enums represent a fixed set of values. They make your schema more expressive and self-documenting.

Example Enum
enum Role {
  ADMIN
  USER
  GUEST
}

type User {
  id: ID!
  name: String!
  role: Role!
}

In this example, the role field can only be one of ADMIN, USER, or GUEST.


Enums in Input Types

Enums are especially useful in input arguments or filters.

input CreateUserInput {
  name: String!
  role: Role!
}

Best Practices

  • ✅ Use enums to restrict valid values (instead of free-form strings)
  • ✅ Validate custom scalars properly to avoid invalid data
  • ✅ Favor scalars for basic values, and use custom ones carefully
  • ✅ Document your enums well for clarity

Tools


Summary

  • Scalars represent primitive leaf values.
  • Enums define a set of constant values.
  • Both are crucial for type safety, validation, and schema clarity.